Let's convert the "A" character to binary format.
private string hex2binary(string hexvalue)When we call hex2binary("A"); it will return "1010" similar samples below;
{
string binaryval = "";
binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
return binaryval;
}
hex2binary("1a"); will return "11010";
hex2bianry("1a2c"); will return "1101000101100"; and so on.
Keep in mind that this hex to binary conversion style uses 32 bit integer number.
20 comments:
Excellent!
Thanks alot!!
Great!
Tahnk you.
very very thank you
super!
Wow
Thank you very much!~
Thanks a lot!!!!!!!!!! :)
Hi I am not able to convert a very large hexa value in binary using the code u provided???? for eg
F23E44810EE1805A0000004004000062
string binaryval = string.Empty;
strInput = "F23E44810EE1805A0000004004000062";
foreach (char ch in strInput)
{
binaryval += Convert.ToString(Convert.ToInt32(ch.ToString(), 16), 2);
}
Console.WriteLine(binaryval);
For large numbers you must use Convert.ToInt64.
strBinValue = Convert.ToString(Convert.ToInt64(strHex, 16), 2);
Thank you!!!!!!!!!!!!!
@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.
Thank You!!!
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
public static string hex2binary(string hexvalue)
{
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:
string binaryval = "";
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;
}
}
return binaryval;
const String strInput = "F23E44810EE1805A0000004004000062";
String result = strInput
.Aggregate(new StringBuilder(), (builder, c) =>
builder.Append(Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')))
.ToString();
Console.WriteLine(result);
It basically does the same as SandeepV's code but it uses PadLeft to save a loop, a StringBuilder for performance on long input strings and LINQ because I can.
Thanks for sharing!
It is working for my application that I am creating!
Regards,
Post a Comment