Hexadecimal to Binary

T

Trecius

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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"


Thank you,


Trecius
 
J

Jon Skeet [C# MVP]

Trecius said:
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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"

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.WriteLine(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(input.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.ToString();
}
}
 
J

Jeroen Mostert

Trecius said:
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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"
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(char hexDigit) {
return hexDigit >= '0' && hexDigit <= '9' ? hexDigit - '0' : hexDigit
- 'A' + 10;
}
static string Hex2Bin(string hexDigits) {
StringBuilder result = new StringBuilder(hexDigits.Length * 4);
foreach (char digit in hexDigits) {
result.Append(binarySequences[hexDigitToInt(digit)]);
}
return result.ToString();
}

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

Arne Vajhøj

Trecius said:
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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"

C# 2.0 / .NET 2.0:

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

sb.Append(Convert.ToString(Convert.ToInt32(c.ToString(), 16),
2).PadLeft(4, '0'));
}
return sb.ToString();
}

C# 3.0 / .NET 3.5:

public static string Hex2Bin35(string s)
{
return String.Join("", (from c in s.ToCharArray() select
Convert.ToString(Convert.ToInt32(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.
 
P

parez

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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"

Thank you,

Trecius


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

Console.WriteLine(Convert.ToString(i, 2));
 
P

parez

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

            Console.WriteLine(Convert.ToString(i, 2));

Sorry.. i didnt read your post all the way
 
A

Arne Vajhøj

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

Console.WriteLine(Convert.ToString(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.ToString(...)"
?

Arne
 
P

parez

Did you read:
   "I've seen other posts, but they are restricted to the size of the
   hexadecimal string, for they use Convert.ToString(...)"
?

Arne

hehe.. I didnt :)
 
F

Fernando Gómez

Trecius said:
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.ToString(...).

EXA:

string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);

This would produce the following output...

"1111101000111000"


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.Globalization.NumberStyles.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.
 
J

Jeroen Mostert

Arne said:
C# 2.0 / .NET 2.0:

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

This is unnecessary; System.String implements IEnumerable<char>.

C# 3.0 / .NET 3.5:

public static string Hex2Bin35(string s)
{
return String.Join("", (from c in s.ToCharArray() select
Convert.ToString(Convert.ToInt32(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.ToString(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.ToString(hexDigit, 2).PadLeft(4, '0')
select binaryDigits
).Aggregate(string.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.
 
A

Arne Vajhøj

Jeroen said:
This is unnecessary; System.String implements IEnumerable<char>.
Thanks.


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.ToString(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.ToString(hexDigit, 2).PadLeft(4, '0')
select binaryDigits
).Aggregate(string.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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top