Reputation: 963
How can I see the bytes/bits of a variable in C? In terms of binary, just zeros and ones.
My problem is that I want to test to see if any zeros exist in the most significant byte of variable x. Any help would be appreciated.
Upvotes: 1
Views: 1803
Reputation: 20262
Use the logical AND operator &
. For example:
char c = ....
if ( (c & 0xFF) == 0xFF) ... // test char c for zeroes
You may want to use shifts and macros to automate it, instead of using numeric constants, because for different types you'll need different values to test the MSB. You can get the value for shifts using sizeof
.
// test MSB of an int for zeroes
int i = ...
if ( ( i & (0xFF << 8*(sizeof(int)-1))) == (0xFF<<8*(sizeof(int)-1))) ...
Upvotes: 3
Reputation: 46
You can use following test
var & (1 << N)
To check if bit N is set in var. Most significant bit depends on the datatype of var.
Upvotes: 1
Reputation: 18008
if(x & 0x80) // assuming x is a byte(char type)
{
// msb is set
}
Upvotes: 0
Reputation: 34618
Print the memory byte by byte, i.e. from 0
to sizeof(x)
(if x
happens to be your variable). Then, when printing each byte, print all eight bits individually.
Upvotes: 0