Mai Wassouf
Mai Wassouf

Reputation: 37

Converting a hexdecimal string to binary string

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?

Upvotes: 1

Views: 89

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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')));

Upvotes: 2

Steve Todd
Steve Todd

Reputation: 1270

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');

Upvotes: 2

Sweeper
Sweeper

Reputation: 271050

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);

Upvotes: 2

Related Questions