c get nth byte of integer
int x = (number >> (8*n)) & 0xff; where n is 0 for the first byte, 1 for the second byte, etc.
int x = (number >> (8*n)) & 0xff; where n is 0 for the first byte, 1 for the second byte, etc.
The paragraph you copied is talking about unsigned types. The behavior is undefined in C++. From the last C++0x draft: The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more … Read more
It doesn’t just convert non-Numbers to Number, it converts them to Numbers that can be expressed as 32-bit unsigned ints. Although JavaScript’s Numbers are double-precision floats(*), the bitwise operators (<<, >>, &, | and ~) are defined in terms of operations on 32-bit integers. Doing a bitwise operation converts the number to a 32-bit signed … Read more
if byte1 is an 8-bit integer type then it’s pointless – if it is more than 8 bits it will essentially give you the last 8 bits of the value: 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 & 0 0 0 0 0 0 0 0 … Read more
Here is an applet where you can exercise some bit-operations, including shifting. You have a collection of bits, and you move some of them beyond their bounds: 1111 1110 << 2 1111 1000 It is filled from the right with fresh zeros. 🙂 0001 1111 >> 3 0000 0011 Filled from the left. A special … Read more
long may be a 64-bit type, but 1 is still an int. You need to make 1 a long int using the L suffix: unsigned long x = 1UL << 32; (You should also make it unsigned using the U suffix as I’ve shown, to avoid the issues of left shifting a signed integer. There’s … Read more
These are Bitwise Operators (reference). x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation. x >>= 1 means “set x … Read more
Right shift of a negative signed number has implementation-defined behaviour. If your 8 bits are meant to represent a signed 8 bit value (as you’re talking about a “signed 32 bit integer” before switching to 8 bit examples) then you have a negative number. Shifting it right may fill “empty” bits with the original MSB … Read more
This is caused due to a combination of an undefined behaviour in C and the fact that code generated for IA-32 processors has a 5 bit mask applied on the shift count. This means that on IA-32 processors, the range of a shift count is 0-31 only. 1 From The C programming language 2 The … Read more
I’d use: if ((value & (1L << x)) != 0) { // The bit was set } (You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)