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.
Excellent!
ReplyDeleteThanks alot!!
Great!
ReplyDeleteTahnk you.
very very thank you
ReplyDeletesuper!
ReplyDeleteWow
ReplyDeleteThank you very much!~
Thanks a lot!!!!!!!!!! :)
ReplyDeleteHi I am not able to convert a very large hexa value in binary using the code u provided???? for eg
ReplyDeleteF23E44810EE1805A0000004004000062
string binaryval = string.Empty;
ReplyDeletestrInput = "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.
ReplyDeletestrBinValue = Convert.ToString(Convert.ToInt64(strHex, 16), 2);
Thank you!!!!!!!!!!!!!
ReplyDelete@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.
ReplyDeleteThank You!!!
ReplyDeletehi, I agree Stonkie zeros lose if first bit is zero of 4 bits' .how can I fix this problem.
ReplyDeleteyou can just do it all as one line, like this
ReplyDeletepublic 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??
ReplyDeleteThanks, I forget this every time. Should probably write it down somewhere handy....
ReplyDeleteI'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)
ReplyDeletejust a modification to the above code, as suggested by stonkie:
ReplyDeletestring 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";
ReplyDeleteString 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!
ReplyDeleteIt is working for my application that I am creating!
Regards,