3

I am trying to convert hex string into binary. My code looks as follows:

sw.Write(Convert.ToString(Convert.ToInt32(value, 16), 2));

However this works for most of the values; But when I convert hex string 0x101 to binarystring, my result is 100000001, rathen than 000100000001. Please help me.

4
  • 4
    Well that is the binary value. Are you saying you need to always pad to a multiple of 4 digits? Commented Jun 12, 2014 at 17:43
  • Does it matter? The leading 0 are not significant... Commented Jun 12, 2014 at 17:53
  • Yes it does matter in my application. So if I have Hex = 001, then Binary should become 000000000001. How do I do this? Commented Jun 12, 2014 at 17:54
  • 1
    if I have Hex = 001. Is Hex an integer or string? Commented Jun 12, 2014 at 17:56

2 Answers 2

5
string Hex = "001";
var s = String.Join("", 
          Hex.Select(x => Convert.ToString(Convert.ToInt32(x+"", 16), 2).PadLeft(4,'0')));
Sign up to request clarification or add additional context in comments.

2 Comments

How do I do the reverse Binary to Hex? Binary string 000001010100 should become 054?
@savi Why do you ask me?
-1

How about using String.PadLeft() ?

string value = "0x001";
string binary = Convert.ToString(Convert.ToInt32(value, 16), 2).PadLeft(12, '0');

3 Comments

You can't just hardcode 12 like that; what if the hex value is 0x1001 ? Then you need to pad to 16 characters..
@ThomasLevesque the 12 in PadLeft() is the total length of the string after padding. msdn.microsoft.com/en-us/library/92h5dc07(v=vs.110).aspx
Yes, I know what PadLeft does... but it will only work for numbers that are less then 12 binary digits. The OP needs to pad to a multiple of 4 digits. If value is 0x1001, the non-padded result will have 13 digits, and padding it to 12 digits will have no effect; you need to pad it to 16 in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.