Search code examples
c#intbyteint32

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


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.


Solution

  • 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.