Jeff - 11 months ago 62

C Question

My head is starting to hurt... I've been looking at this way too long.

I'm trying to mask the most significant nibble of an int, regardless of the int bit length and the endianness of the machine. Let's say

`x = 8425`

`0010 0000 1110 1001`

`0x20E9`

`9`

`x & 0xF`

`9`

`2`

I apologize if my logic from here on out falls apart, my brain is completely fried, but here I go:

My book tells me that the bit length w of the data type int can be computed with

`w = sizeof(int)<<3`

`0xF << w-4`

`1111`

`0000`

`1111 0000 0000 0000`

`0xF >> w-8`

`0000 0000 0000 1111`

`0xF`

`0000`

Answer Source

Bit shifting operators operate at a level of abstraction above endianness. "Left" shifts always shift towards the most significant bit, and "right" shifts always shift towards the least significant bit.