By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,451 Members | 1,613 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,451 IT Pros & Developers. It's quick & easy.

Hexadecimal to Binary

P: n/a
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
Jun 27 '08 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Trecius <Tr*****@discussions.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.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();
}
}

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2

P: n/a
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.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.)
--
J.
Jun 27 '08 #3

P: n/a
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.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.ToStr ing(), 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.
Jun 28 '08 #4

P: n/a
On Jun 27, 6:56*pm, Trecius <Trec...@discussions.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.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));
Jun 28 '08 #5

P: n/a
On Jun 27, 10:18*pm, parez <psaw...@gmail.comwrote:
On Jun 27, 6:56*pm, Trecius <Trec...@discussions.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.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));
Sorry.. i didnt read your post all the way
Jun 28 '08 #6

P: n/a
parez wrote:
On Jun 27, 6:56 pm, Trecius <Trec...@discussions.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.ToString(...).

EXA:

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

This would produce the following output...

"1111101000111000"

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
Jun 28 '08 #7

P: n/a
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...@discussions.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.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));

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.tostring.
Jun 28 '08 #8

P: n/a
On Jun 27, 10:21*pm, Arne Vajhj <a...@vajhoej.dkwrote:
parez wrote:
On Jun 27, 6:56 pm, Trecius <Trec...@discussions.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.ToString(...).
EXA:
string str = "FA38";
string binStr = SomeClass.Hex2Bin(str);
This would produce the following output...
"1111101000111000"
* * * * * * 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
hehe.. I didnt :)
Jun 28 '08 #9

P: n/a
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.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.
Jun 28 '08 #10

P: n/a
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.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())
This is unnecessary; System.String implements IEnumerable<char>.

<snip>
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.

--
J.
Jun 28 '08 #11

P: n/a
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.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())

This is unnecessary; System.String implements IEnumerable<char>.
Thanks.
<snip>
>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);
}
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
Jun 28 '08 #12

This discussion thread is closed

Replies have been disabled for this discussion.