Re: How do I convert a ASCII Byte Array, to another Byte Array
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/02/05
- Next message: sudhakar: "Securing assembly/dlls - unable to add secured component in design time"
- Previous message: filburt1: "UDP sockets"
- In reply to: Russell Mangel: "How do I convert a ASCII Byte Array, to another Byte Array"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 2 Feb 2005 18:01:14 -0000
Russell Mangel <russell@tymer.net> wrote:
> 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[i] = (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");
}
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: sudhakar: "Securing assembly/dlls - unable to add secured component in design time"
- Previous message: filburt1: "UDP sockets"
- In reply to: Russell Mangel: "How do I convert a ASCII Byte Array, to another Byte Array"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|