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") 
2
  • Can you show the code you're currently using to do the conversion? Commented Jun 12, 2014 at 22:29
  • Convert.ToInt32(value,2).ToString("X") Commented Jun 12, 2014 at 22:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. fine for small numbers. Consider "x"+(value.Length / 4) as format if need to handle 1-4 hex digits.
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"))
);

1 Comment

+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.

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.