Home > Software design >  How to merge bytes together in C language
How to merge bytes together in C language

Time:05-21

X and Y analog values is made of 2 bytes

Byte1 : 0 B13 B12 B11 B10 B9 B8 B7 
Byte2 : 0 B6 B5 B4 B3 B2 B1 B0 

The final X and Y analog value is:

0 0 B13 B12 B11 B10 B9 B8 B7  B6 B5 B4 B3 B2 B1 B0

I don't have very good way to implement. Any suggestions? Thank you,

CodePudding user response:

I believe you are talking about having a 14 bit ADC value that is split into HIGH and Low bytes separately. From your question I am assuming the Low byte has bits [6-0] and the High byte has bits [13-7]. You can make them a single value by shifting bits appropriately.

uint16_t value = (high_byte << 7) | low_byte;

How does this work? You shift high_byte 7 times to the left.

High_byte : b13 b12 b11 b10 b09 b08 b07   0   0   0   0   0   0   0 (shifted 7 times)
Low_byte  :   0   0   0   0   0   0   0 b06 b05 b04 b03 b02 b01 b00

Finally ORing this gives you the result.

CodePudding user response:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t byte1 = 0b01010101;  // 0x55 in hex
    uint8_t byte2 = 0b01111111;  // 0x7F in hex
    
    uint16_t result = (byte1<<7) | byte2;
    // Expected result: 0b0010101011111111
    // which is Hex: 0x2AFF
    
    printf("0xX\n", result);

    return 0;
}

I think this example code illustrates what you are describing.

byte1 and byte2 are chosen with recognizable bit-patterns:

  • byte1: high bit is zero, other bits are alternating.
  • byte2: high bit is zero, other bits are all set

Then I shift byte1 over 7 times so that B13 has two leading zeros, as you described, and OR in byte2

  •  Tags:  
  • c
  • Related