Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a word from Byte []?

Tags:

c

I am new to programming world, I want to convert two bytes into a word.

So basically, I have a Byte array where index 0 is Buffer[0]=08 and index 1 is Buffer[1]=06 I want to create a word from these two bytes

where word ETHType to be 0x0806

like image 801
Om Choudhary Avatar asked Jan 26 '23 19:01

Om Choudhary


2 Answers

You would use bitwise operators and bit shifting.

uint16_t result = ((uint16_t)Buffer[0] << 8) | Buffer[1];

This does the following:

  • The value of Buffer[0] is shifted 8 bits to the left. That gives you 0x0800
  • A bitwise OR is performed between the prior value and the value of Buffer[1]. This sets the low order 8 bits to Buffer[1], giving you 0x0806
like image 69
dbush Avatar answered Jan 29 '23 20:01

dbush


word ETHType = 0;
ETHType = (Buffer[0] << 8) | Buffer[1];

edit: You should probably add a mask to each operation to make sure there is no bit overlap, and you can do it safely in one line.

word ETHType = (unsigned short)(((unsigned char)(Buffer[0] & 0xFF) << 8) | (unsigned char)(Buffer[1] & 0xFF)) & 0xFFFF;
like image 30
Z4ckZ3r0 Avatar answered Jan 29 '23 19:01

Z4ckZ3r0