Kyle Weller
Kyle Weller

Reputation: 2623

C: Check least significant and most significant byte for a 0 or 1

I am trying to check the least and most significant byte of an int separately.

I want to check if any bit in the least significant byte is one. I want to return 1 if true and 0 if false. My attempt:

int lsb_one(int x) {
  return ( (x & 0xffff) != 0 );
}

I want to check if any bit in the most significant byte is zero. I want to return 1 if true and 0 if false. My attempt:

int msb_zero(int x) {
  return ( (~(x & 0x0000ffff)) != 0 );
}

Any pointers?

Upvotes: 1

Views: 5158

Answers (2)

Masked Man
Masked Man

Reputation: 11045

As other answers have already pointed out, your mask should be 0xff instead of 0xffff since a byte is usually 8 bits. To keep the msb_zero function implementation independent, use CHAR_BIT and sizeof() as follows:

#include <limits.h>

int msb_zero(int x) {
  return (x & (0xff << (sizeof(int) * CHAR_BIT - CHAR_BIT))) != 0;
}

The CHAR_BIT in limits.h provides you the number of bits is a char/byte.

Edit For completeness, the lsb_one function:

int lsb_one(int x) {
    return ((x & 0xff) != 0 );
}

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67223

Try:

int lsb_one(int x) {
    return ((x & 0xff) != 0 );
}

int msb_zero(int x) {
    return ((x & 0xff000000) != 0xff000000);
}

Note that the second version is platform dependent, assuming that int is a 32-bit value.

Upvotes: 3

Related Questions