How to combine two bytes into an int in C

‮ww‬w.lautturi.com
How to combine two bytes into an int in C

In standard C, there is no byte type, which corresponds to an unsigned char.
In a general C compiler, integer is 16 bits and byte is 8 bits.
We can combine two bytes into one int.

/*
Example: 2 bytes to 1 integer in C language
*/

#include <stdio.h>
#include <stdlib.h>
typedef unsigned char byte; // Custom byte type

int main(int argc, char const *argv[]) {

    byte buf[2] = {2,4};
    int number = buf[0] | buf[1] << 8;

    printf("int value :%d",number);

    return 0;
}
Created Time:2017-08-22 15:12:37  Author:lautturi