Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...