简体   繁体   English

如何在 Java 中将有符号字节数组转换为 ascii

[英]How to convert signed byte array to ascii in Java

In Java program I have signed byte array as在 Java 程序中,我将字节数组签名为

[-112, 21, 64, 0, 7, 50, 54, 127]

how i can convert into ascii number which is equal to我如何转换成等于的ascii码

901540000732367F

It seems that the order of bytes in the result is reverse to that of the array, so you should iterate the array in the reverse order and add each element with a shift by the predefined number of bits:结果中的字节顺序似乎与数组的字节顺序相反,因此您应该以相反的顺序迭代数组并添加每个元素并按预定义的位数进行移位:

private static String convertToHexFullByte(byte[] arr) {
    return convertToHex(arr, 8);
}
    
private static String convertToHexHalfByte(byte[] arr) {
    return convertToHex(arr, 4);
}
    
private static String convertToHex(byte[] arr, int bits) {
    long mask = 0;
    for (int i = 0; i < bits; i++) {
        mask |= 1 << i;
    }
    long res = 0;
    for (int i = arr.length - 1, j = 0; i >= 0; i--, j += bits) {
        res |= (arr[i] & mask) << j;
    }

    return Long.toHexString(res).toUpperCase();        
}

Test测试

public static void main(String args[]) {
    byte[] arr4 = {49, 55, 48, 51, 55};
        
    System.out.println(convertToHexHalfByte(arr4));
        
    byte[] arr8 = {-112, 21, 64, 0, 7, 50, 54, 127};
        
    System.out.println(convertToHexFullByte(arr8));
}

output output

17037
901540000732367F

Try this.试试这个。 It works by:它的工作原理是:

  • streaming the indices of the byte array流式传输字节数组的索引
  • maping to an int and getting rid of the sign extension映射到一个 int 并去掉符号扩展
  • reducing to a long by shift and or operations.通过轮班和/或操作减少到 long。
byte[] bytes = { -112, 21, 64, 0, 7, 50, 54, 127 };

long lng = IntStream.range(0, bytes.length)
        .mapToLong(i -> bytes[i] & 0xff)
        .reduce(0L, (a, b) -> (a << 8) | b);

System.out.println("long decimal value = " + lng);
System.out.println("long hex value = " + Long.toHexString(lng));    

prints印刷

long decimal value = -8064469188872096129
long hex value = 901540000732367f

Using the same technique, the other example of {49, 55, 48, 51, 55} should be:使用相同的技术, {49, 55, 48, 51, 55}的另一个例子应该是:

long decimal value = 211379303223
long hex value = 3137303337

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

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