473,398 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

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

EXA:

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

This would produce the following output...

"1111101000111000"
Thank you,
Trecius
Jun 27 '08 #1
11 7653
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
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
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
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
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
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
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
On Jun 27, 10:21*pm, Arne Vajhűj <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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Cesar Andres Roldan Garcia | last post by:
Hi I'm trying to write an hexadecimal file... I mean not a text plain... I have to convert a float decimal number in float hexadecimal one, and that's done. That number is the one I'm gonna...
2
by: akash deep batra | last post by:
hi i want to convert a 96 bit binary number into a hexadecimal number. e.g binary number= 001100010001010000100101011110111111010101110100010110000101011000101010000000000000000000000000 how...
6
by: MrKrich | last post by:
I want to convert Hexadecimal or normal integer to Binary. Does VB.Net has function to do that? I only found Hex function that convert normal integer to Hexadecimal.
15
by: jaks.maths | last post by:
How to convert negative integer to hexadecimal or octal number? Ex: -568 What is the equivalent hexadecimal and octal number??
8
by: Vijay | last post by:
Hi , I am doing a small project in c. I have a Hexadecimal file and want to convert into ascii value. (i.e., Hexadecimal to Ascii conversion from a file). Could anyone help me? Thanks in...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
6
by: Andrea | last post by:
Hi, suppose that I have a string that is an hexadecimal number, in order to print this string I have to do: void print_hex(unsigned char *bs, unsigned int n){ int i; for (i=0;i<n;i++){...
6
by: sweeet_addiction16 | last post by:
hello Im writin a code in c... can sum1 pls help me out in writing a c code to convert decimalnumber to hexadecimal number.The hexadecimal number generated has to be an unsigned long.
14
by: Ellipsis | last post by:
Ok so I am converting to hexadecimal from decimal and I can only cout the reverse order of the hexadecimal?! How could I reverse this so its the right order? Heres my code: #include <iostream>...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.