Converting binary to hexadecimal?

前端 未结 5 1802
逝去的感伤
逝去的感伤 2020-12-22 04:35

Just wondering on how I would go about converting binary to hexadecimal?? Would I first have to convert the binary to decimal and then to hexadecimal??

For example,

5条回答
  •  被撕碎了的回忆
    2020-12-22 05:29

    No, you don't convert to decimal and then to hexadecimal, you convert to a numeric value, and then to hexadecimal.

    (Decimal is also a textual representation of a number, just like binary and hexadecimal. Although decimal representation is used by default, a number doesn't have a textual representation in itself.)

    As a hexadecimal digit corresponds to four binary digits you don't have to convert the entire string to a number, you can do it four binary digits at a time.

    First fill up the binary number so that it has full groups of four digits:

    000101101001.1011101010100110

    Then you can convert each group to a number, and then to hexadecimal:

    0001 0110 1001.1011 1010 1010 0110

    169.BAA6

    Alternatively, you can split the number into the two parts before and after the period and convert those from binary. The part before the period can be converted stright off, but the part after has to be padded to be correct.

    Example in C#:

    string binary = "101101001.101110101010011";
    
    string[] parts = binary.Split('.');
    while (parts[1].Length % 4 != 0) {
      parts[1] += '0';
    }
    
    string result =
      Convert.ToInt32(parts[0], 2).ToString("X") +
      "." +
      Convert.ToInt32(parts[1], 2).ToString("X");
    

提交回复
热议问题