Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

You can use the BitConverter class to convert an array of bytes to an int.

// Add the bytes to an array, starting with b3, then b2, b1 and 0 to
// make it 4 bytes in total.
byte[] b = new byte[] { 0xC2, 0x06, 0x00, 0x00 };
int i = BitConverter.ToInt32(b, 0);

i will now have the value 1730.

You can try this:

    byte b1 = (byte)0x00;
    byte b2 = (byte)0x06;
    byte b3 = (byte)0xC2;
    int i = ((b1 & 0xFF) << 16) | ((b2 & 0xFF) << 8) | (b3 & 0xFF);

EDIT:

    byte b1 = (byte)0x00;
    byte b2 = (byte)0x06;
    byte b3 = (byte)0xC2;
    int i = (b1 << 16) | (b2 << 8) | b3;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top