What is the purpose of the unsigned right shift operator “>>>” in Java?

The >>> operator lets you treat int and long as 32- and 64-bit unsigned integral types, which are missing from the Java language. This is useful when you shift something that does not represent a numeric value. For example, you could represent a black and white bit map image using 32-bit ints, where each int … Read more

“Isolate” specific Row/Column/Diagonal from a 64-bit number

Here’s a solution with only 4 main steps: const uint64_t column_mask = 0x8080808080808080ull; const uint64_t magic = 0x2040810204081ull; int get_col(uint64_t board, int col) { uint64_t column = (board << col) & column_mask; column *= magic; return (column >> 56) & 0xff; } It works like this: the board is shifted to align the column with … Read more

Find out number of bits needed to represent a positive integer in binary?

Well, the answer is pretty simple. If you have an int value: int log2(int value) { return Integer.SIZE – Integer.numberOfLeadingZeros(value); } The same exists for Long… [Edit] If shaving milliseconds is an issue here, Integer.numberOfLeadingZeros(int) is reasonably efficient, but still does 15 operations… Expanding a reasonable amount of memory (300 bytes, static) you could shave … Read more

Need help understanding “getbits()” method in Chapter 2 of K&R C

Let’s use 16 bits for our example. In that case, ~0 is equal to 1111111111111111 When we left-shift this n bits (3 in your case), we get: 1111111111111000 because the 1s at the left are discarded and 0s are fed in at the right. Then re-complementing it gives: 0000000000000111 so it’s just a clever way … Read more

Send and receive binary data over web sockets in Javascript?

The next draft (hybi-07) of the WebSockets specification is being implemented in most browsers and it will add built-in binary support to the protocol and API. However, until then, WebSockets payload is encoded as UTF-8. In order to send binary data you must use some way of encoding the binary data as UTF-8. There are … Read more

Why does ((unsigned char)0x80)

C compiler performs integer promotions before executing the shift. Rule 6.3.1.1 of the standard says: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. Since all values of unsigned char can be … Read more

Why is squaring a number faster than multiplying two random numbers?

There exist algorithms more efficient than O(N^2) to multiply two numbers (see Karatsuba, Pollard, Schönhage–Strassen, etc.) The two problems “multiply two arbitrary N-bit numbers” and “Square an arbitrary N-bit number” have the same complexity. We have 4*x*y = (x+y)^2 – (x-y)^2 So if squaring N-bit integers takes O(f(N)) time, then the product of two arbitrary … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)