杰瑞科技汇

java int to hex

Of course! Converting an int to its hexadecimal (hex) string representation is a common task in Java. There are several ways to do it, each with slightly different behavior.

java int to hex-图1
(图片来源网络,侵删)

Here are the most common methods, from the simplest to the most flexible.

The Simplest Way: Integer.toHexString()

This is the most direct and commonly used method. It takes an integer and returns its hexadecimal representation as a String, without any leading "0x" prefix.

Key Point: This method returns the hex representation of the integer's two's complement value. For positive numbers, this is straightforward. For negative numbers, it will show the hex of the positive number that, when inverted and added to 1, gives the original negative number.

Example:

public class IntToHexExample {
    public static void main(String[] args) {
        int positiveNumber = 255;
        int negativeNumber = -255;
        int zero = 0;
        // Convert to hex
        String hexPositive = Integer.toHexString(positiveNumber);
        String hexNegative = Integer.toHexString(negativeNumber);
        String hexZero = Integer.toHexString(zero);
        System.out.println("Integer: " + positiveNumber + " -> Hex: " + hexPositive);
        System.out.println("Integer: " + negativeNumber + " -> Hex: " + hexNegative);
        System.out.println("Integer: " + zero + " -> Hex: " + hexZero);
    }
}

Output:

Integer: 255 -> Hex: ff
Integer: -255 -> Hex: 1ff01  // This is the two's complement representation
Integer: 0 -> Hex: 0

Controlling Case (Lowercase vs. Uppercase)

By default, Integer.toHexString() produces lowercase letters (a-f). If you need uppercase letters (A-F), you can use the String.toUpperCase() method.

Example:

int number = 3735928559; // This is 0xDEADBEEF
String hexLower = Integer.toHexString(number);
String hexUpper = hexLower.toUpperCase();
System.out.println("Lowercase: " + hexLower); // Output: deadbeef
System.out.println("Uppercase: " + hexUpper); // Output: DEADBEEF

Adding the "0x" Prefix

Sometimes you want the standard 0x prefix to make it clear that the string is a hexadecimal value. You can simply concatenate it.

Example:

int number = 255;
String hexValue = Integer.toHexString(number);
String prefixedHex = "0x" + hexValue;
System.out.println(prefixedHex); // Output: 0xff

Formatting with Leading Zeros

A common requirement is to format the hex string to have a fixed number of digits, padding it with leading zeros. For a standard 32-bit int, this is 8 digits (32 bits / 4 bits per hex digit).

The best way to do this is with String.format().

Example:

int number = 255;
// %08x means:
// % - start of format specifier
// 0 - pad with leading zeros
// 8 - total width of 8 characters
// x - format as hexadecimal (lowercase)
String formattedHex = String.format("%08x", number);
System.out.println("Formatted (8 digits): " + formattedHex); // Output: 000000ff
// For uppercase, use %08X
String formattedHexUpper = String.format("%08X", number);
System.out.println("Formatted (8 digits, uppercase): " + formattedHexUpper); // Output: 000000FF

This is extremely useful for representing colors (e.g., ARGB values) or memory addresses.


Handling Negative Numbers Correctly

If you want to treat the integer as an unsigned value (i.e., get the hex for the positive number that int would represent if it were a long), you should first cast it to a long.

The long value is then passed to Long.toHexString().

Example:

int negativeInt = -1;
// The two's complement hex of -1
String signedHex = Integer.toHexString(negativeInt);
System.out.println("Signed (two's complement): " + signedHex); // Output: ffffffff
// The unsigned hex representation
// Cast to long first, then convert
String unsignedHex = Long.toHexString((long) negativeInt & 0xFFFFFFFFL);
System.out.println("Unsigned (as if it were a positive 32-bit number): " + unsignedHex); // Output: ffffffff

Explanation: In Java, int is signed. The value -1 is stored in memory as 0xFFFFFFFF. Integer.toHexString(-1) correctly shows you this. However, if you just want the hex string for the bit pattern 0xFFFFFFFF regardless of its signed meaning, casting to long first is the right approach. The & 0xFFFFFFFFL is a common idiom to ensure the long is treated as a 32-bit unsigned value.


Summary: Which Method to Use?

Your Goal Recommended Method Example Code
Quick & simple conversion Integer.toHexString() Integer.toHexString(255);
Uppercase hex letters Integer.toHexString() + toUpperCase() Integer.toHexString(255).toUpperCase();
Hex with 0x prefix "0x" + Integer.toHexString() "0x" + Integer.toHexString(255);
Fixed width with leading zeros (e.g., 8 digits) String.format() String.format("%08X", 255);
Unsigned representation of a negative int Long.toHexString((long) myInt & 0xFFFFFFFFL) Long.toHexString((long) -1 & 0xFFFFFFFFL);
分享:
扫描分享到社交APP
上一篇
下一篇