2

I´m new in the C language, and I´m trying to get the 4 least significant bits from an unsigned char. So far I have no idea how to get them. I´ll appreciate any help

Clifford
  • 82,791
  • 12
  • 81
  • 153
Santiago Fajardo
  • 119
  • 1
  • 1
  • 8

1 Answers1

5

It's simple bitwise logic:

unsigned char c = 120;
unsigned char lsb4 = c & 0x0F;

Where 0x0F represents the binary value 00001111.

If you're using GCC, it's even more literal:

unsigned char lsb4 = c & 0b00001111;

Technically the leading 0s are not required here but they're included to help illustrate which bits are being selected.

tadman
  • 200,744
  • 21
  • 223
  • 248