Hexadecimal to Binary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?VHJlY2l1cw==?=

    Hexadecimal to Binary

    Hello, Newsgroupians:

    I've a question regarding Hexadecimal to binary conversion.

    Suppose I have a long hexadecimal string, and I would like to convert it to
    a binary string. How can I accomplish this with minimal code? I've seen
    other posts, but they are restricted to the size of the hexadecimal string,
    for they use Convert.ToStrin g(...).

    EXA:

    string str = "FA38";
    string binStr = SomeClass.Hex2B in(str);

    This would produce the following output...

    "11111010001110 00"


    Thank you,


    Trecius
  • Jon Skeet [C# MVP]

    #2
    Re: Hexadecimal to Binary

    Trecius <Trecius@discus sions.microsoft .comwrote:
    I've a question regarding Hexadecimal to binary conversion.
    >
    Suppose I have a long hexadecimal string, and I would like to convert it to
    a binary string. How can I accomplish this with minimal code? I've seen
    other posts, but they are restricted to the size of the hexadecimal string,
    for they use Convert.ToStrin g(...).
    >
    EXA:
    >
    string str = "FA38";
    string binStr = SomeClass.Hex2B in(str);
    >
    This would produce the following output...
    >
    "11111010001110 00"
    Given that there are only 16 hex digits, and each hex digit maps to
    exactly 4 characters, it's relatively straightforward . There are no
    doubt ways to do it with shorter code than this, but this way is pretty
    simple:


    using System;
    using System.Text;

    class Test
    {
    static void Main()
    {
    string binStr = HexToBin("FA38" );
    Console.WriteLi ne(binStr);
    }

    static readonly string[] Nybbles =
    {"0000", "0001", "0010", "0011",
    "0100", "0101", "0110", "0111",
    "1000", "1001", "1010", "1011",
    "1100", "1101", "1110", "1111"};
    static string HexToBin(string input)
    {
    StringBuilder builder = new StringBuilder(i nput.Length*4);
    foreach (char c in input)
    {
    if (c >= '0' && c <='9')
    {
    builder.Append( Nybbles[c-'0']);
    }
    else if (c >= 'a' && c <= 'f')
    {
    builder.Append( Nybbles[c-'a'+10]);
    }
    else if (c >= 'A' && c <= 'F')
    {
    builder.Append( Nybbles[c-'A'+10]);
    }
    else
    {
    throw new FormatException ("Invalid hex digit: "+c);
    }
    }
    return builder.ToStrin g();
    }
    }

    --
    Jon Skeet - <skeet@pobox.co m>
    Web site: http://www.pobox.com/~skeet
    Blog: http://www.msmvps.com/jon_skeet
    C# in Depth: http://csharpindepth.com

    Comment

    • Jeroen Mostert

      #3
      Re: Hexadecimal to Binary

      Trecius wrote:
      I've a question regarding Hexadecimal to binary conversion.
      >
      Suppose I have a long hexadecimal string, and I would like to convert it to
      a binary string. How can I accomplish this with minimal code? I've seen
      other posts, but they are restricted to the size of the hexadecimal string,
      for they use Convert.ToStrin g(...).
      >
      EXA:
      >
      string str = "FA38";
      string binStr = SomeClass.Hex2B in(str);
      >
      This would produce the following output...
      >
      "11111010001110 00"
      >
      There are 16 hexadecimal digits, corresponding to 16 4-bit patterns. So the
      idiot's way of doing it (also called "the simplest thing that could possibly
      work") would be

      private static readonly string[] binarySequences = new string[] {
      "0000", "0001", "0010", "0011",
      "0100", "0101", "0110", "0111",
      "1000", "1001", "1010", "1011",
      "1100", "1101", "1110", "1111",
      };

      static int hexDigitToInt(c har hexDigit) {
      return hexDigit >= '0' && hexDigit <= '9' ? hexDigit - '0' : hexDigit
      - 'A' + 10;
      }
      static string Hex2Bin(string hexDigits) {
      StringBuilder result = new StringBuilder(h exDigits.Length * 4);
      foreach (char digit in hexDigits) {
      result.Append(b inarySequences[hexDigitToInt(d igit)]);
      }
      return result.ToString ();
      }

      And despite being the idiot's way, this is actually not bad. (Once you put
      in validation, that is.)


      --
      J.

      Comment

      • =?UTF-8?B?QXJuZSBWYWpow7hq?=

        #4
        Re: Hexadecimal to Binary

        Trecius wrote:
        Suppose I have a long hexadecimal string, and I would like to convert it to
        a binary string. How can I accomplish this with minimal code? I've seen
        other posts, but they are restricted to the size of the hexadecimal string,
        for they use Convert.ToStrin g(...).
        >
        EXA:
        >
        string str = "FA38";
        string binStr = SomeClass.Hex2B in(str);
        >
        This would produce the following output...
        >
        "11111010001110 00"
        C# 2.0 / .NET 2.0:

        public static string Hex2Bin20(strin g s)
        {
        StringBuilder sb = new StringBuilder() ;
        foreach(char c in s.ToCharArray() )
        {

        sb.Append(Conve rt.ToString(Con vert.ToInt32(c. ToString(), 16),
        2).PadLeft(4, '0'));
        }
        return sb.ToString();
        }

        C# 3.0 / .NET 3.5:

        public static string Hex2Bin35(strin g s)
        {
        return String.Join("", (from c in s.ToCharArray() select
        Convert.ToStrin g(Convert.ToInt 32(c.ToString() , 16), 2).PadLeft(4,
        '0')).ToArray() );
        }

        Arne

        PS: I think I would use the 2.0 version on 3.5 as well - it is
        more readable.

        Comment

        • parez

          #5
          Re: Hexadecimal to Binary

          On Jun 27, 6:56 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
          Hello, Newsgroupians:
          >
          I've a question regarding Hexadecimal to binary conversion.
          >
          Suppose I have a long hexadecimal string, and I would like to convert it to
          a binary string.  How can I accomplish this with minimal code?  I've seen
          other posts, but they are restricted to the size of the hexadecimal string,
          for they use Convert.ToStrin g(...).
          >
          EXA:
          >
          string str = "FA38";
          string binStr = SomeClass.Hex2B in(str);
          >
          This would produce the following output...
          >
          "11111010001110 00"
          >
          Thank you,
          >
          Trecius

          int i = Convert.ToInt32 ("FA38", 16);

          Console.WriteLi ne(Convert.ToSt ring(i, 2));

          Comment

          • parez

            #6
            Re: Hexadecimal to Binary

            On Jun 27, 10:18 pm, parez <psaw...@gmail. comwrote:
            On Jun 27, 6:56 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
            >
            >
            >
            Hello, Newsgroupians:
            >
            I've a question regarding Hexadecimal to binary conversion.
            >
            Suppose I have a long hexadecimal string, and I would like to convert it to
            a binary string.  How can I accomplish this with minimal code?  I've seen
            other posts, but they are restricted to the size of the hexadecimal string,
            for they use Convert.ToStrin g(...).
            >
            EXA:
            >
            string str = "FA38";
            string binStr = SomeClass.Hex2B in(str);
            >
            This would produce the following output...
            >
            "11111010001110 00"
            >
            Thank you,
            >
            Trecius
            >
                        int i = Convert.ToInt32 ("FA38", 16);
            >
                        Console.WriteLi ne(Convert.ToSt ring(i, 2));
            Sorry.. i didnt read your post all the way

            Comment

            • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

              #7
              Re: Hexadecimal to Binary

              parez wrote:
              On Jun 27, 6:56 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
              >I've a question regarding Hexadecimal to binary conversion.
              >>
              >Suppose I have a long hexadecimal string, and I would like to convert it to
              >a binary string. How can I accomplish this with minimal code? I've seen
              >other posts, but they are restricted to the size of the hexadecimal string,
              >for they use Convert.ToStrin g(...).
              >>
              >EXA:
              >>
              >string str = "FA38";
              >string binStr = SomeClass.Hex2B in(str);
              >>
              >This would produce the following output...
              >>
              >"1111101000111 000"
              >
              int i = Convert.ToInt32 ("FA38", 16);
              >
              Console.WriteLi ne(Convert.ToSt ring(i, 2));
              Did you read:
              "I've seen other posts, but they are restricted to the size of the
              hexadecimal string, for they use Convert.ToStrin g(...)"
              ?

              Arne

              Comment

              • parez

                #8
                Re: Hexadecimal to Binary

                On Jun 27, 10:20 pm, parez <psaw...@gmail. comwrote:
                On Jun 27, 10:18 pm, parez <psaw...@gmail. comwrote:
                >
                >
                >
                On Jun 27, 6:56 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
                >
                Hello, Newsgroupians:
                >
                I've a question regarding Hexadecimal to binary conversion.
                >
                Suppose I have a long hexadecimal string, and I would like to convertit to
                a binary string.  How can I accomplish this with minimal code?  I've seen
                other posts, but they are restricted to the size of the hexadecimal string,
                for they use Convert.ToStrin g(...).
                >
                EXA:
                >
                string str = "FA38";
                string binStr = SomeClass.Hex2B in(str);
                >
                This would produce the following output...
                >
                "11111010001110 00"
                >
                Thank you,
                >
                Trecius
                >
                            int i = Convert.ToInt32 ("FA38", 16);
                >
                            Console.WriteLi ne(Convert.ToSt ring(i, 2));
                >
                Sorry.. i didnt read your post all the way
                but you could do it for each character in the string and append the
                output of convert.tostrin g.

                Comment

                • parez

                  #9
                  Re: Hexadecimal to Binary

                  On Jun 27, 10:21 pm, Arne Vajhøj <a...@vajhoej.d kwrote:
                  parez wrote:
                  On Jun 27, 6:56 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
                  I've a question regarding Hexadecimal to binary conversion.
                  >
                  Suppose I have a long hexadecimal string, and I would like to convert it to
                  a binary string.  How can I accomplish this with minimal code?  I've seen
                  other posts, but they are restricted to the size of the hexadecimal string,
                  for they use Convert.ToStrin g(...).
                  >
                  EXA:
                  >
                  string str = "FA38";
                  string binStr = SomeClass.Hex2B in(str);
                  >
                  This would produce the following output...
                  >
                  "11111010001110 00"
                  >
                              int i = Convert.ToInt32 ("FA38", 16);
                  >
                              Console.WriteLi ne(Convert.ToSt ring(i, 2));
                  >
                  Did you read:
                     "I've seen other posts, but they are restricted to the size of the
                     hexadecimal string, for they use Convert.ToStrin g(...)"
                  ?
                  >
                  Arne
                  hehe.. I didnt :)

                  Comment

                  • =?UTF-8?B?RmVybmFuZG8gR8OzbWV6?=

                    #10
                    Re: Hexadecimal to Binary

                    Trecius wrote:
                    Hello, Newsgroupians:
                    >
                    I've a question regarding Hexadecimal to binary conversion.
                    >
                    Suppose I have a long hexadecimal string, and I would like to convert it to
                    a binary string. How can I accomplish this with minimal code? I've seen
                    other posts, but they are restricted to the size of the hexadecimal string,
                    for they use Convert.ToStrin g(...).
                    >
                    EXA:
                    >
                    string str = "FA38";
                    string binStr = SomeClass.Hex2B in(str);
                    >
                    This would produce the following output...
                    >
                    "11111010001110 00"
                    >
                    >
                    Thank you,
                    >
                    >
                    Trecius
                    Hi there,

                    how about this? It uses int.Parse, hope that's ok.

                    string ToBin(string str)
                    {
                    string hex;
                    string bin;
                    int num;

                    bin = string.Empty;
                    hex = str;
                    num = int.Parse(hex, System.Globaliz ation.NumberSty les.HexNumber);

                    while (num 0)
                    {
                    bin = string.Format(" {0}{1}", (num & 1) == 1 ? "1" : "0", bin);
                    num >>= 1;
                    }

                    return bin;
                    }

                    I did a little test, it seems to be working fine.

                    Regards.


                    Comment

                    • Jeroen Mostert

                      #11
                      Re: Hexadecimal to Binary

                      Arne Vajhøj wrote:
                      Trecius wrote:
                      >Suppose I have a long hexadecimal string, and I would like to convert
                      >it to a binary string. How can I accomplish this with minimal code?
                      >I've seen other posts, but they are restricted to the size of the
                      >hexadecimal string, for they use Convert.ToStrin g(...).
                      >>
                      >EXA:
                      >>
                      >string str = "FA38";
                      >string binStr = SomeClass.Hex2B in(str);
                      >>
                      >This would produce the following output...
                      >>
                      >"1111101000111 000"
                      >
                      C# 2.0 / .NET 2.0:
                      >
                      public static string Hex2Bin20(strin g s)
                      {
                      StringBuilder sb = new StringBuilder() ;
                      foreach(char c in s.ToCharArray() )
                      This is unnecessary; System.String implements IEnumerable<cha r>.

                      <snip>
                      C# 3.0 / .NET 3.5:
                      >
                      public static string Hex2Bin35(strin g s)
                      {
                      return String.Join("", (from c in s.ToCharArray() select
                      Convert.ToStrin g(Convert.ToInt 32(c.ToString() , 16), 2).PadLeft(4,
                      '0')).ToArray() );
                      }
                      >
                      Without skipping on LINQ, this can easily be made more readable if desired:

                      public static string Hex2Bin(string hexDigits) {
                      return string.Concat(
                      (
                      from c in hexDigits
                      let hexDigit = Convert.ToInt32 (c.ToString(), 16)
                      let binaryDigits = Convert.ToStrin g(hexDigit, 2).PadLeft(4, '0')
                      select binaryDigits
                      ).ToArray()
                      );
                      }

                      Or to stay in LINQ altogether:

                      public static string Hex2Bin(string hexDigits) {
                      return (
                      from c in hexDigits
                      let hexDigit = Convert.ToInt32 (c.ToString(), 16)
                      let binaryDigits = Convert.ToStrin g(hexDigit, 2).PadLeft(4, '0')
                      select binaryDigits
                      ).Aggregate(str ing.Concat);
                      }

                      All that said, I would still prefer the "stupid" method of concatenating the
                      nybble strings yourself. While code like this makes the most out of reusing
                      existing code, I don't think it gains much on clarity, certainly not when
                      you throw in LINQ to impress your fellow programmers with.

                      --
                      J.

                      Comment

                      • =?UTF-8?B?QXJuZSBWYWpow7hq?=

                        #12
                        Re: Hexadecimal to Binary

                        Jeroen Mostert wrote:
                        Arne Vajhøj wrote:
                        >Trecius wrote:
                        >>Suppose I have a long hexadecimal string, and I would like to convert
                        >>it to a binary string. How can I accomplish this with minimal code?
                        >>I've seen other posts, but they are restricted to the size of the
                        >>hexadecimal string, for they use Convert.ToStrin g(...).
                        >>>
                        >>EXA:
                        >>>
                        >>string str = "FA38";
                        >>string binStr = SomeClass.Hex2B in(str);
                        >>>
                        >>This would produce the following output...
                        >>>
                        >>"111110100011 1000"
                        >>
                        >C# 2.0 / .NET 2.0:
                        >>
                        > public static string Hex2Bin20(strin g s)
                        > {
                        > StringBuilder sb = new StringBuilder() ;
                        > foreach(char c in s.ToCharArray() )
                        >
                        This is unnecessary; System.String implements IEnumerable<cha r>.
                        Thanks.
                        <snip>
                        >C# 3.0 / .NET 3.5:
                        >>
                        > public static string Hex2Bin35(strin g s)
                        > {
                        > return String.Join("", (from c in s.ToCharArray() select
                        >Convert.ToStri ng(Convert.ToIn t32(c.ToString( ), 16), 2).PadLeft(4,
                        >'0')).ToArray( ));
                        > }
                        >>
                        Without skipping on LINQ, this can easily be made more readable if desired:
                        >
                        public static string Hex2Bin(string hexDigits) {
                        return string.Concat(
                        (
                        from c in hexDigits
                        let hexDigit = Convert.ToInt32 (c.ToString(), 16)
                        let binaryDigits = Convert.ToStrin g(hexDigit, 2).PadLeft(4, '0')
                        select binaryDigits
                        ).ToArray()
                        );
                        }
                        >
                        Or to stay in LINQ altogether:
                        >
                        public static string Hex2Bin(string hexDigits) {
                        return (
                        from c in hexDigits
                        let hexDigit = Convert.ToInt32 (c.ToString(), 16)
                        let binaryDigits = Convert.ToStrin g(hexDigit, 2).PadLeft(4, '0')
                        select binaryDigits
                        ).Aggregate(str ing.Concat);
                        }
                        Many ways of doing this.

                        But I don't really consider those more readable.

                        All that said, I would still prefer the "stupid" method of concatenating
                        the nybble strings yourself. While code like this makes the most out of
                        reusing existing code, I don't think it gains much on clarity, certainly
                        not when you throw in LINQ to impress your fellow programmers with.
                        That was my conclusion as well. Bytes are pretty cheap.

                        Arne


                        Comment

                        Working...