简体   繁体   中英

Look at the bytes/bits of a variable in C

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.

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))) ...

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.

Print the memory byte by byte, ie from 0 to sizeof(x) (if x happens to be your variable). Then, when printing each byte, print all eight bits individually.

if(x & 0x80) // assuming x is a byte(char type)
{
   // msb is set
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM