Reputation: 495
I'm writing a small test program that converts 64-bit numbers from little-endian to big endian format.
int main(void){
uint64_t value1 = 1234;
uint64_t value2 = 0;
uint64_t constant = 0xFF00000000000000;
uint8_t i;
for(i = 0; i < 4; i++){
int8_t shift = 56 - 16 * i; // Gives me the sequence 56, 40, 24, 8.
value2 |= (value1 & constant) >> shift;
constant = constant >> 2;
}
for(i = 0; i < 4; i++){
int8_t shift = 16 * i + 8; // Gives me the sequence 8, 24, 40, 56. value2 |= (value1 & constant) << shift;
constant = constant >> 2;
}
printf("\n\nvalue1: %" PRIu64, value1);
printf("\nvalue2: %" PRIu64, value2);
}
It's a little convoluted, but it's the bitwise shift operations I have a problem with. The line
constant = constant >> 2;
doesn't give me what I expect. I expect 0xFF00000000000000
to become 0x00FF000000000000
after one loop, and so on. Instead, it becomes 0x3FC0000000000000
.
I assume there's also a similar problem with the other shift operations. Can anyone explain?
My first guess is that bitwise operators only work correctly on 32-bit numbers. In which case, I could cast a 32-bit pointer and deal with each 32-bit block one at a time. But I'd like to avoid that since it's even more convoluted.
Upvotes: 0
Views: 902
Reputation: 935
This has to be when working with bitwise operator. Look at the simple explanation below.
In your case 0xFF0000...000
is actually 0b111111110000...000
in binary representation. When you must have read about 0000 to 1111 in binary is actually 0 to F in hex representation. This bitwise operator operates bit-level so this hex representation needs to be broken to a binary before we look into further.
Now shifting 2 bits give out 0b001111111100...000
. Observing closely, this is 0b<0011><1111><1100>00...000
which is actually 0x3FC00...000
Hope it explained!
Upvotes: 2
Reputation: 176
The >> operator does a bit-shift by the amount of bits at the right of the operator. You should use constant >> 8
if you want to move over 1 bytes (2 nibbles). It works exactly the same no matter the size of the variable on which the shift is being applied.
Upvotes: 0