0

I am trying to convert Binary string to hex, however I miss the zero values, I mean Binary string 000001010100 should become hex string 054?

I'm currently using

Convert.ToInt32(value,2).ToString("X") 
savi
  • 497
  • 2
  • 12
  • 27

2 Answers2

2

You can split the string in four digit parts, parse them and format into a hex digit. That gives you the correct number of digits. Example:

string bin = "000001010100";
string hex = String.Concat(
  Regex.Matches(bin, "....").Cast<Match>()
  .Select(m => Convert.ToInt32(m.Value, 2)
  .ToString("x1"))
);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • +1. Handles arbitrary length of strings as long it is aligned to 4 bits. If need to also handle non-aligned strings consider `for` loop and cut out sub-strings instead of `Regex`. – Alexei Levenkov Jun 12 '14 at 23:03
2

You can simply use

Convert.ToInt32(value,2).ToString("X3")

where the number following the X is the minimum number of digits you want in the final string. I used the number 3, because that was the output you included as an example. It's explained in more detail in this Microsoft documentation.