rohi
rohi

Reputation:

32 bit hex in one variable

How can I put this hex 0x0a01 into a 32 bit var in C. What I'm trying to do is to parse a protocol. Part of the it has a length value. The problem is that I'm getting the received packet as an array, so the length 0x0a01 would be 0x0a on lets say [1] and 0x01 on [2], and I want them both to be 0a01 in one var so I can run a compare to a constant or use in a for loop.

Upvotes: 2

Views: 1077

Answers (2)

ouah
ouah

Reputation: 145899

uint32_t var;
char buff[128];

...

var = ((buff[1] & 0xFF) << 8) | (buff[2] & 0xFF);

Notice we use (buff[1] & 0xFF) << 8 and not buff[1] << 8, because if buff is a char array and char is signed, sign extension would occur on the promoted buff[1] when the value is negative.

Upvotes: 0

ratchet freak
ratchet freak

Reputation: 48216

ah 32 bit is a int in most current platforms (or int32_t defined in stdint.h)

and bit operations are made for this:

int var = buff[1]<<8|buff[2];

<< is the left shift so 0x0a gets transformed into 0x0a00 and | is the or operator so that is gets combined properly

Upvotes: 6

Related Questions