How do I convert a ASCII Byte Array, to another Byte Array

  • Thread starter Thread starter Russell Mangel
  • Start date Start date
R

Russell Mangel

I need to convert the following Byte Array, the bytes are are encoded as
ASCII.
Byte[] asciiBytes =
{0x30,0x31,0x30,0x35,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,
0x35,0x31,0x35,0x30,0x30,0x30,0x30,0x30,0x30,0x39,0x42,0x31,0x31,0x38,0x31,0
x35,0x34,0x36,0x30,0x32,0x31,0x35,0x39,0x37,0x31,0x34,0x46,0x36,0x35,0x41,0x
42,0x32,0x45,0x45,0x44,0x30,0x33,0x30,0x30,0x30,0x30};

To This Byte Array
Byte[] bytes =
{0x01,0x05,0x00,0x00,0x00,0x00,0x00,0x05,0x15,0x00,0x00,0x00,0x9B,0x11,0x81,
0x54,0x60,0x21,0x59,0x71,0x4F,0x65,0xAB,0x2E,0xED,0x03,0x00,0x00};

I have to convert 0x30 and 0x31 to 0x01, then 0x30 and 0x35 to 0x5, and so
on.

How would I go about doing this?

Thanks
Russell Mangel
Las Vegas, NV
 
Do I miss something or your need is just to add low bytes for two
consecutives item in the array ?

int i, j;
j = 0;
for (int i=0; i < asciiBytes.Length ; i += 2)
bytes[j++] = asciiBytes & 0x0F + asciiBytes & 0x0F;



Lionel.
 
Russell Mangel said:
I need to convert the following Byte Array, the bytes are are encoded as
ASCII.
Byte[] asciiBytes =
{0x30,0x31,0x30,0x35,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,
0x35,0x31,0x35,0x30,0x30,0x30,0x30,0x30,0x30,0x39,0x42,0x31,0x31,0x38,0x31,0
x35,0x34,0x36,0x30,0x32,0x31,0x35,0x39,0x37,0x31,0x34,0x46,0x36,0x35,0x41,0x
42,0x32,0x45,0x45,0x44,0x30,0x33,0x30,0x30,0x30,0x30};

To This Byte Array
Byte[] bytes =
{0x01,0x05,0x00,0x00,0x00,0x00,0x00,0x05,0x15,0x00,0x00,0x00,0x9B,0x11,0x81,
0x54,0x60,0x21,0x59,0x71,0x4F,0x65,0xAB,0x2E,0xED,0x03,0x00,0x00};

I have to convert 0x30 and 0x31 to 0x01, then 0x30 and 0x35 to 0x5, and so
on.

How would I go about doing this?

Something like this does it:

public static byte[] ParseHex(byte[] hex)
{
byte[] result = new byte[hex.Length/2];
int hexIndex=0;
for (int i=0; i < result.Length; i++)
{
result = (byte)(ParseHexDigit(hex[hexIndex++])*16+
ParseHexDigit(hex[hexIndex++]));

}
return result;
}

static int ParseHexDigit(byte c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'a' && c <= 'f')
{
return c-'a'+10;
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
throw new ArgumentException ("Invalid hex character");
}
 
Back
Top