Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2 bytes into an integer

Tags:

I receive a port number as 2 bytes (least significant byte first) and I want to convert it into an integer so that I can work with it. I've made this:

char buf[2]; //Where the received bytes are  char port[2];  port[0]=buf[1];   port[1]=buf[0];  int number=0;  number = (*((int *)port)); 

However, there's something wrong because I don't get the correct port number. Any ideas?

like image 501
user1367988 Avatar asked Jun 12 '13 17:06

user1367988


People also ask

How do you convert bytes to integers?

A byte value can be interchanged to an int value using the int. from_bytes() function. The int. from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.

Is integer 2 or 4 bytes?

The size of an int is really compiler dependent. Back in the day, when processors were 16 bit, an int was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems. Still, using sizeof(int) is the best way to get the size of an integer for the specific system the program is executed on.


1 Answers

I receive a port number as 2 bytes (least significant byte first)

You can then do this:

  int number = buf[0] | buf[1] << 8; 
like image 59
nos Avatar answered Sep 21 '22 07:09

nos