1

I have string

w0 = "2B7E1516"

I want to convert it to a binary string in order to be

"00101011011111100001010100010110" 

However i keep getting only "101011011111100001010100010110":

w0 = "2B7E1516";
char paddingChar = '0';
w0 = Convert.ToString(Convert.ToInt32(w0, 16), 2).PadLeft(8, paddingChar);

The problem is in 2 it converts it to only "10" not to "0010", how can i fix that?

3 Answers 3

2

Your output string is a 32 bit number, so the last line should be:

wo = Convert.ToString(Convert.ToInt32(w0, 16), 2).PadLeft(32, '0');
Sign up to request clarification or add additional context in comments.

Comments

2

You only made it pad left 8 characters. If the resulting strings is more than 9 characters, it won't add more 0s to the left.

You should instead pad left by a multiple of 4. Which multiple of 4? That depends on the length of the hex string. Specifically, you should pad left by w0.Length * 4:

w0 = Convert.ToString(Convert.ToInt32(w0, 16), 2).PadLeft(w0.Length * 4, paddingChar);

Comments

2

Let's convert each char within the string with padding to 4 digits:

 '0' ->    "0" -> "0000"
 '1' ->    "1" -> "0001"
 '2' ->   "10" -> "0010"  
  ...
 'F' -> "1111" -> "FFFF"

Code:

  string w0 = "2B7E1516";

  // Since we convert string char by char the initial string can be arbitrary long
  string result = string.Concat(w0.Select(c =>
    ('0' <= c && c <= '9' ? Convert.ToString(c - '0', 2) :
     'a' <= c && c <= 'f' ? Convert.ToString(c - 'a' + 10, 2) :
                            Convert.ToString(c - 'A' + 10, 2)).PadLeft(4, '0')));

Comments

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.