Web Development Blog
Web development blog, including simple php, mysql, c#, html, js, nginx tips and tutorials.
27 November 2008
C# Convert Hexadecimal to Binary String Conversion
Let's convert the "A" character to binary format. When we call hex2binary("A"); it will return "1010" similar samples below;
21 comments:
very very thank you
Thank you very much!
Hi I am not able to convert a very large hexa value in binary using the code u provided. for eg
string binaryval = string.Empty;
binaryval += Convert.ToString(Convert.ToInt32(ch.ToString(), 16), 2);
For large numbers you must use Convert.ToInt64.
strBinValue = Convert.ToString(Convert.ToInt64(strHex, 16), 2);
@ck I didn't try, but I think you'll lose zeros when parsing characters that translate to less than 4 bits. You should add them by padding each value with zeros up to 4 bits.
hi, I agree Stonkie zeros lose if first bit is zero of 4 bits' .how can I fix this problem.
you can just do it all as one line, like this
return Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
Is this valid to Convert the hexadecimal to 4 bit binary too??
Thanks, I forget this every time. Should probably write it down somewhere handy.
I'll have to implement this into my code tonight when I get back to my place, should do what I want hopefully. (Let's say I have a file that was way to large LOL)
just a modification to the above code, as suggested by stonkie:
binaryval = Convert.ToString(Convert.ToInt32(hexString, 16), 2);
if (binaryval.Length != hexString.Length * 4)
int bitsdifference = hexString.Length * 4 - binaryval.Length;
for (int i = 0; i < bitsdifference; i++)
binaryval = "0" + binaryval;
const String strInput = "F23E44810EE1805A0000004004000062";
.Aggregate(new StringBuilder(), (builder, c) =>