Michael
Michael

Reputation: 8761

bitwise operations in C receiving binary in a char

I am receiving 2 bytes of binary information via Serial in C.

I am receiving them in a char.

So I need to join the 2 chars to make a int but Im unsure how to do that.. first of all the first byte is in binary format and not char format.. So im unsure how I Can convert it into a useable form for my program.

Upvotes: 0

Views: 141

Answers (5)

cnicutar
cnicutar

Reputation: 182754

Just OR them together ?

x = (b1 << 8) | b2;

Make sure they're unsigned or cast accordingly (shifting signed stuff is nasty).

Upvotes: 4

ouah
ouah

Reputation: 145919

if MSB (Most Significant Byte) comes first:

unsigned char array[2];
...
int bla;
bla = array[1] | (array[0] << 8);

if LSB (Least Significant Byte) comes first:

bla = array[0] | (array[1] << 8);

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882646

For a start, it would be better to receive them in an unsigned char just so you have no issues with sign extension and the like.

If you want to combine them, you can use something like:

int val = ch1; val = val << 8 | ch2;

or:

int val = ch2; val = val << 8 | ch1;

depending on the endian-ness of your system, and assuming your system has an eight-bit char type.

Upvotes: 1

pmg
pmg

Reputation: 108986

use unsigned char to avoid sign-extension problems.

val16 = char1 * 256 + char2;

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182885

You can use something like this:

int my_int=char1;
myint<<=8;
myint|=char2;

This assumes char1 contains the most significant byte. Switch the 1 and 2 otherwise.

Upvotes: 1

Related Questions