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
354 views
in Technique[技术] by (71.8m points)

c - insert array of hex codes into an integer

I'm trying to do something that I thought would be pretty basic but either I'm just ignoring something obvious or it is actually a bit tricky. My problem is: I have an array of 4 chars that contains 4 hex values. For example:

array[0] = 0xD8
array[1] = 0xEC
array[2] = 0xA2 
array[3] = 0x83

I want to store this array in an integer with the combined value, in this case 0xD8ECA283

I've tried doing logical OR and then shifting the bits and with this method I managed to store the value of 0xD8 in the integer, but not the rest. Any tips would be appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use the binary or operator, and an integer whose precision is guaranteed to be at least 32 bits, which is the type unsigned long (although the type uint_least32_t could be also used).

Unsigned integer is used so any potential undefined and/or implementation defined behavior that is present when shifting signed integers is avoided.

This solution is independent of endianness.

unsigned long a = ( ( ( unsigned long )array[0] & 0xFF ) << 24 ) |
                  ( ( ( unsigned long )array[1] & 0xFF ) << 16 ) |
                  ( ( ( unsigned long )array[2] & 0xFF ) << 8 ) |
                  ( ( ( unsigned long )array[3] & 0xFF ) << 0 ) ;

Casts to ( unsigned long ) are made to avoid intermediate implicit conversion to int.
The & 0xFF operation is there to remove unnecessary bits(if there were any in an unlikely scenario where CHAR_BIT != 8).


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

...