two bytes to int c

Solutions on MaxInterview for two bytes to int c by the best coders in the world

showing results for - "two bytes to int c"
Giulio
29 Jul 2017
1// bytes_to_int_example.cpp
2// Output: port = 514
3
4// I am assuming that the bytes the bytes need to be treated as 0-255 and combined MSB -> LSB
5
6// This creates a macro in your code that does the conversion and can be tweaked as necessary
7#define bytes_to_u16(MSB,LSB) (((unsigned int) ((unsigned char) MSB)) & 255)<<8 | (((unsigned char) LSB)&255) 
8// Note: #define statements do not typically have semi-colons
9#include <stdio.h>
10
11int main()
12{
13  char buf[2];
14  // Fill buf with example numbers
15  buf[0]=2; // (Least significant byte)
16  buf[1]=2; // (Most significant byte)
17  // If endian is other way around swap bytes!
18
19  unsigned int port=bytes_to_u16(buf[1],buf[0]);
20
21  printf("port = %u \n",port);
22
23  return 0;
24}
25