简体   繁体   中英

java - Enforce 4 digit hex representation of a binary number

Below is a snippet of my java code.

//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
    BigInteger temp = new BigInteger(binaryNumber, 2);
        return temp.toString(16).toUpperCase();
}

If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits? Thanks.

You do one of the following:

  • Manually pad with zeroes
  • Use String.format()

Manually pad with zeroes

Since you want extra leading zeroes when shorter than 4 digits, use this:

BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
    hex = "000".substring(hex.length() - 1) + hex;
return hex;

Use String.format()

BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);

Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger .

In Java 8, do it by parsing the binary input as an unsigned number:

int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);

The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.

I customized your code a bit to include leading zeros based on input string:

public static void main(String[] args) {
    System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
    BigInteger temp = new BigInteger(binaryNumber, 2);
    String hexStr = temp.toString(16).toUpperCase();
    int b16inLen = binaryNumber.length()/4;
    int b16outLen =  hexStr.length();
    int b16padding = b16inLen - b16outLen;
    for (int i=0; i<b16padding; i++) {
        hexStr=('0'+hexStr);
    }
    return hexStr;
}

Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM