Re: How to convert string "AD-A6-0D-1F" to byte[]?
From: Daniel Jin (DanielJin_at_discussions.microsoft.com)
Date: 01/27/05
- Next message: Julia: "Re: Cannot connect to a remote object hosted in a window service"
- Previous message: Alvin Bruney [MVP]: "Thread synchronization question"
- In reply to: Jon Skeet [C# MVP]: "Re: How to convert string "AD-A6-0D-1F" to byte[]?"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 27 Jan 2005 05:55:05 -0800
or you can try Int32.Parse( string, NumberStyles.HexNumber ), then convert
int to byte[]. that too however doesn't support the '-', so you have to
strip them out.
"Jon Skeet [C# MVP]" wrote:
> Maqsood Ahmed <maqsood_ahmed@gawab.com> wrote:
> > For ASCII:
> > System.Text.Encoding.ASCII.GetBytes(string); //returns byte array.
> > For Unicode:
> > System.Text.Encoding.Unicode.GetBytes(string); //returns bytes array
> > (little-endian byte format)
> >
> > Cheers :)
>
> Those will certainly convert strings to bytes, but not in the way that
> the OP wants.
>
> However, you don't need to get the substring of the string for each
> pair of hex digits. Here's some code I wrote a while ago to parse hex
> strings. It *doesn't* take account of the '-' between each pair of hex
> digits, but could easily be modified to do so.
>
> static int ParseHexDigit(char 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");
> }
>
> public static string ParseHex(string hex)
> {
> char[] result = new char[hex.Length/2];
> int hexIndex=0;
> for (int i=0; i < result.Length; i++)
> {
> result[i] = (char)(ParseHexDigit(hex[hexIndex++])*16+
> ParseHexDigit(hex[hexIndex++]));
>
> }
> return new string (result);
> }
>
> --
> Jon Skeet - <skeet@pobox.com>
> http://www.pobox.com/~skeet
> If replying to the group, please do not mail me too
>
- Next message: Julia: "Re: Cannot connect to a remote object hosted in a window service"
- Previous message: Alvin Bruney [MVP]: "Thread synchronization question"
- In reply to: Jon Skeet [C# MVP]: "Re: How to convert string "AD-A6-0D-1F" to byte[]?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|