简体   繁体   English

Integer 到 Java 中的两位十六进制数

[英]Integer to two digits hex in Java

I need to change a integer value into 2-digit hex value in Java.Is there any way for this.我需要将 integer 值更改为 Java 中的 2 位十六进制值。有什么办法吗? Thanks谢谢

My biggest number will be 63 and smallest will be 0. I want a leading zero for small values.我最大的数字是 63,最小的数字是 0。我想要一个小值的前导零。

String.format("%02X", value);

如果您按照 aristar 的建议使用X而不是x ,那么您不需要使用.toUpperCase()

Integer.toHexString(42);

Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int) Javadoc: http : //docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)

Note that this may give you more than 2 digits, however!请注意,这可能会给您超过 2 位数字,但是! (An Integer is 4 bytes, so you could potentially get back 8 characters.) (整数是 4 个字节,因此您可能会返回 8 个字符。)

Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):只要您绝对确定您只处理单字节值(255 或更少),这里有一些技巧来获取您的填充:

Integer.toHexString(0x100 | 42).substring(1)

Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java . 在 Java 中用零填充左填充整数(非十进制格式)的更多(更好)解决方案。

String.format("%02X", (0xFF & value));    

Use Integer.toHexString() .使用Integer.toHexString() Dont forget to pad with a leading zero if you only end up with one digit.如果最后只有一位数,请不要忘记用前导零填充。 If your integer is greater than 255 you'll get more than 2 digits.如果您的整数大于 255,您将得到 2 位以上的数字。

StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
    sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();

If you just need to print them try this:如果您只需要打印它们,请尝试以下操作:

for(int a = 0; a < 255; a++){
    if( a % 16 == 0){
        System.out.println();
    }
    System.out.printf("%02x ", a);
}

i use this to get a string representing the equivalent hex value of an integer separated by space for every byte EX : hex val of 260 in 4 bytes = 00 00 01 04我用它来获得一个字符串,该字符串表示一个整数的等效十六进制值,每个字节用空格分隔EX:4 个字节中 260 的十六进制值 = 00 00 01 04

    public static String getHexValString(Integer val, int bytePercision){
    StringBuilder sb = new StringBuilder();
    sb.append(Integer.toHexString(val));

    while(sb.length() < bytePercision*2){
        sb.insert(0,'0');// pad with leading zero
    }

    int l = sb.length(); // total string length before spaces
    int r = l/2; //num of rquired iterations

    for (int i=1; i < r;  i++){
        int x = l-(2*i); //space postion
        sb.insert(x, ' ');
    }
    return sb.toString().toUpperCase();         
}

public static void main(String []args){
    System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}

根据 GabrielOshiro 的说法,如果要将整数格式化为长度 8,请尝试此操作

String.format("0x%08X", 20) //print 0x00000014

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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