How to append two bytes in C

I am fairly new to programming in C and I have a problem that I have to fix. When I receive my data the most significant bit is printed like 00f1 and my least significant bit is printed 005e. How do I get it so that the value can be 00f15e? As of right now I can only get them to print 5ef100



answered 2 months ago Jose #1

Let's suppose that you are talking about bytes instead of bits, the MSB is 0xf1, the LSB is 0x5e and you want to get all together in 2bytes:

uint16_t result = ((uint16_t)MSB<<8) | (LSB);

(The number 8 must be replaced by a define in order to avoid magic numbers)

answered 2 months ago PSkocik #2

Use bit ops:

#include <stdio.h>
typedef unsigned char uchar;
int main()
    uchar m=0xf1;
    uchar l=0x5e;
    unsigned ml=((unsigned)m)<<8|(unsigned)l; 
    //doing it in unsigned (at least 16 bits guaranteed, no sign bit)
    printf("%06x\n", ml); //prints 00f15e

comments powered by Disqus