Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the lower 8 bits of an int?

Tags:

c

Lets say I have an int variable n = 8. On most machines this will be a 32 bit value. How can I only get the lower 8 bits (lowest byte) of this in binary? Also how can I access each bit to find out what it is?

like image 431
Laz Avatar asked Jul 17 '10 04:07

Laz


1 Answers

unsigned n = 8; unsigned low8bits = n & 0xFF; 

Note a few things:

  1. For bitwise operations, always use the unsigned types
  2. Bits can be extracted from numbers using binary masking with the & operator
  3. To access the low 8 bits the mask is 0xFF because in binary it has its low 8 bits turned on and the rest 0
  4. The low 8 bits of the number 8 are... 8 (think about it for a moment)

To access a certain bit of a number, say the kth bit:

unsigned n = ...; unsigned kthbit = (1 << k) & n; 

Now, kthbit will be 0 if the kth bit of n is 0, and some positive number (2**k) if the kth bit of n is 1.

like image 136
Eli Bendersky Avatar answered Sep 23 '22 10:09

Eli Bendersky