Posts

Showing posts with the label bitwise_ops

Repeating strings efficiently

Recently, Michael Ficarra pointed me to an efficient algorithm for repeating a string several times. In this blog post, I explain how it works. The algorithm makes use of the fact that natural numbers (non-negative integers) can be represented as sums of powers of two. Natural numbers as sums of powers of two You can express any natural number as a sum of powers of two. In fact, that’s what a number in binary notation is. The value of a sequence of n binary digits d i d n-1 d n-2 ... d 0 is the sum ∑ 0 ≤ i < n d i × 2 i = d 0 × 1 + d 1 × 2 + d 2 × 4 + ... Each digit d i is either one or zero. Therefore, each addend is either a power of two or it is zero. The algorithm Roughly, the algorithm iterates over the digits starting with d 0 . After each iteration, it doubles str , the string to repeat. If the current digit is one then the current value of str is added to the result. In other words, if the digit d i is one, 2 i times str is added to the result. The ...

Binary bitwise operators in JavaScript

This blog post describes JavaScript’s binary bitwise operators: bitwise And ( & ), bitwise Or ( | ), and bitwise Xor ( ^ ). These operators work with 32-bit integers. That is, they convert their operands to 32-bit integers and produce a result that is a 32-bit integer (encoded as a floating point number, at least externally). Inputting and outputting binary numbers In the following examples, we work with binary numbers, via the following two operations: parseInt(str, 2) parses a string str in binary notation (base 2). For example: > parseInt('110', 2) 6 num.toString(2) converts the number num to a string in binary notation. For example: > 6..toString(2) '110' Binary bitwise operators Bitwise And: number1 & number2 > (parseInt('11001010', 2) & parseInt('1111', 2)).toString(2) '1010' Bitwise Or: number1 | number2 > (parseInt('11001010', 2) | parseInt('1111', 2)).toString(2) ...