Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add 3 bytes and return an integer number?

Tags:

c#

int

byte

int32

Lets assume that I have a hex string of

00 00 04 01 11 00 08 00 06 C2 C1 BC

With this the 7th, 8th, and 9th octet are a number I need to generate. The hex is

00 06 C2

This number turns out to be 1730. With the following, how can I simplify this?

byte b1 = 0x00;
byte b2 = 0x06;
byte b3 = 0xC2;

Console.WriteLine(Convert.ToInt32((Convert.ToString(b1, 16)) + (Convert.ToString(b2, 16)) + (Convert.ToString(b3, 16)), 16));

I know there has to be a simpler way. I tried Console.WriteLine((b1 + b2 + b3).ToString()); but it doesn't work.

like image 329
Gabriel Graves Avatar asked Dec 04 '25 10:12

Gabriel Graves


1 Answers

Try:

int result = b3 | (b2 << 8) | (b1 << 16);

Assuming that b1, b2 and b3 are the byte values that you need to convert.

The << operator shifts its operand left by the specified number of bits.

like image 122
Matthew Watson Avatar answered Dec 07 '25 00:12

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!