Reputation: 527
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")
Upvotes: 0
Views: 3740
Reputation: 16259
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.
Upvotes: 2
Reputation: 700262
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"))
);
Upvotes: 2