开发者

How can access individual number of an array element in C?

开发者 https://www.devze.com 2023-01-10 15:21 出处:网络
If I have some array element, how can I getindividual numbers from the array element buffer[0]? For example, suppose I have buffer[0]=0x0605040302, I\'d like to first extract 2, then 0, then 6,开发者

If I have some array element, how can I get individual numbers from the array element buffer[0]?

For example, suppose I have buffer[0]=0x0605040302, I'd like to first extract 2, then 0, then 6,开发者_如何学C etc.


The array element content is ONE number. You are trying to extract A DIGIT out of it. Look for masking and shifting - the & and >> operators.

EDIT:

A mask is a string of "0"s and "1"s that let you isolate bits of interest out of a number. A mask containing the hex digit 0xF is used to isolate individual hex digits in a number. For example:

num = 0x4321 (= 0100_0011_0010_0001)
mask = 0x00f0 (= 0000_0000_1111_0000)
num & mask = 0x0020 (= 0000_0000_0010_0000)

Shifting a number effectively brings the required bit to a required position in a number. So, shifting a number to the right by n positions will bring bit #n to place #0.

num = 0x4321 (= 0100_0101_0010_0001)
num >> 8 = 0x0043 (= 0000_0000_0100_0011)

Combine the two operations and you have your extracted digit!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号