Re: How to convert string "AD-A6-0D-1F" to byte[]?

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: Daniel Jin (DanielJin_at_discussions.microsoft.com)
Date: 01/27/05


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
>



Relevant Pages

  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... conformant string. ... int repeats, reps; ... ref satisfierLength); ...
    (comp.programming)
  • RE: Controling Modal Dialogs (Solution)
    ... doesn't return until the 'modal' browser returns. ... string varOptions) ... public void DocumentComplete ... int rc = winDisp.Invoke(rgDispId, ref guid, 0, ...
    (microsoft.public.inetsdk.programming.webbrowser_ctl)
  • Gcc compatible header file
    ... A string collection is a table of zero terminated strings that will grow ... typedef struct _StringCollection StringCollection; ... int; ... bool; ...
    (comp.lang.c)
  • Kernighan and Pikes "Beautiful" Code
    ... conformant string. ... int repeats, reps; ... ref satisfierLength); ...
    (comp.programming)
  • Re: FTP CD command
    ... public const int GENERIC_WRITE = 0x40000000; ... string lpszProxyName, ... public static extern IntPtr InternetConnect ( ... public static extern bool FtpGetCurrentDirectory ( ...
    (microsoft.public.dotnet.languages.vb)