There is the following code:

long hex; const string Text = "D0 9F D0 BE D1 81 D1 82 D0 BE D0 B9 "+ "2C 20 D0 BF D0 B0 D1 80 D0 BE D0 B2 D0 BE D0 B7 2C 20 D0 "+ "BD D0 B5 20 D1 81 D1 82 D1 83 D1 87 D0 B8 D1 82 D0 B5 20 "+ "D0 BA D0 BE D0 BB D0 B5 D1 81 D0 B0 2E"; string[] words = Text.Split(' '); foreach (string word in words) { hex = Convert.ToInt32(word, 16); Console.WriteLine("{0:x} : шестнадцатеричная : " + String.Format("{0:00000000}",Convert.ToString(hex, 2)), hex); } Console.ReadLine(); 

According to the logic in the console, I want to output the value of the converted values, but contrary to the specified String.Format value, when outputting to the console, the zeros from the left are truncated. How to set the format correctly so that 8 bits are output to the console?

  • You have a handler in the loop eating and so on 8 bits. What do you have, and what do you want to get? - nick_n_a
  • some values, for example, 20 is converted to 00100000, and displayed in the console 100000, how to get the format {00000000} - Garrus_En
  • I just understood, the fact is that the formatting string :000000 does not apply to the string type. Alternatively, you can reparate it in long, then for long the formatter will add zeros, but for string it will definitely not. You have even answered almost the same. - nick_n_a

2 answers 2

As an option via PadLeft

 ... Console.WriteLine($"{hex:x} : шестнадцатеричная : {Convert.ToString(hex,2).PadLeft(8, '0')}"); ... 

Add the missing zeros to the left.

    The answer from @Vladislav Khapin is correct, I’ll just explain why {0:00000000}" did not work. The fact is that the format character 0 affects only numeric arguments. But you have this argument as a string, not a number.

    As for the output of numbers with alignment with zeros, no one will write better than MSDN: How to: Pad a Number with Leading Zeros .