current position:Home>What exactly does byte & 0xff do in Java?

What exactly does byte & 0xff do in Java?

2022-11-24 22:18:05Oxy

先说结论

byte & 0xff 是将byte从(-128 至 127)转化成 int(Converted range of values: 0 至 255).

其实就是1个byte有两种表示方法,我们既可以用-128 - 127This range represents a byte,也可以用 0 - 255This range of numbers represents a byte.

看一个demo

用Java中的InetAddressclass to get my current ip

public class InetAddressTest {
     
    public static void main(String[] args) throws UnknownHostException {
    
        InetAddress localHost = InetAddress.getLocalHost();
        byte[] address = localHost.getAddress();
        for (byte b : address) {
    
            System.out.print(b + " ");
        }
    }
}

输出结果

-64 -88 2 119

本机ip
在这里插入图片描述

好像不太一样,我们ipaddress only 0 - 255来表示,不会出现负数.

So change it to another way of writing,The bytes that will be fetched & 0xff

public class InetAddressTest {
     
    public static void main(String[] args) throws UnknownHostException {
    
        InetAddress localHost = InetAddress.getLocalHost();
        byte[] address = localHost.getAddress();
        for (byte b : address) {
    
            System.out.print( ( b & 0xff ) + " ");
        }
    }
}

结果

192 168 2 119

Process finished with exit code 0

Sure enough, it was the result we wanted

为什么需要转换

因为Java中的byte是有符号的,His range can only be -128 - 127.

我们在使用tcpWhile waiting for an agreement,The first thing to do is to convert the transmitted message into a byte stream,然后再传输,In programming languages, byte streams are usually in decimalbyte数组来表示.
在这里插入图片描述

If we want to use it 0-255to represent a byte,Don't want to use negative numbers,该怎么办呢?

可惜Java中没有 无符号字节(unsigned byte), 我们只能用 int 来存储0-255.

而int的范围是(-2^31 ~ 2^31-1),只用了256个,The rest of the space is wasted,得不偿失啊.

So when we store、It can be used when transferringbyte,But when you use it, you need to do a conversion,那为什么0xffYou can get unsignedbyte呢.

& 0xff的作用

as a hexadecimal number,0xff在JavaWhat type of storage is used in it?

在这里插入图片描述

It should be obvious,0xff是整型.

Suppose I want to convert now 字节 -1

-1的原码、反码、The complements are as follows:

原码  1 0 0 0  0 0 0 1
反码  0 1 1 1  1 1 1 0
补码  0 1 1 1  1 1 1 1

现在和 0xff做运算, ff 就是(1111 11111),And because he is an integer,占4个字节,32为,所以0Xff的前面还有24个0.

用 -1 的补码进行计算

-1                                      0 1 1 1  1 1 1 1
0xff     000000000 000000000 000000000  1 1 1 1  1 1 1 1
=        000000000 000000000 000000000  0 1 1 1  1 1 1 1
=        255

其实在Java中,”任何数 & 0Xffequal to that number itself“ This sentence does not appear to be so correct

”任意整型 & 0xff = 本身“ 是没有问题的

但是字节 & 0xff was dragged to another dimension,从byte进化成了int.

关于byte[ ] & 0xFF的问题

I've been writing about it recentlySHA256加密解密的问题,Found a piece of code like this,I understood it out of curiosity.

private static String byte2Hex(byte[] bytes){
    
  StringBuffer stringBuffer = new StringBuffer();
  String temp = null;
  for (int i=0;i<bytes.length;i++){
    
   temp = Integer.toHexString(bytes[i] & 0xFF);
   if (temp.length()==1){
    
    //1得到一位的进行补0操作
    stringBuffer.append("0");
   }
   stringBuffer.append(temp);
  }
  return stringBuffer.toString();
 }

Integer类中toHexString方法的参数是int类型,为什么byte[ ] & 0xFF可以表示int类型呢?

byte[i]是8位二进制,0xFF转化为8位二进制为11111111,& The result after that is still itself,这是怎么回事?

We all know that the storage in the computer is stored using two's complement.

复习一下,The three concepts of the original code inverse code and complement code

For the highest bit of a byte,There are rules in the computer,The highest digit of a positive number is 0,负数的最高位为1.

对于正数(00000001)In terms of original code,首位表示符号位,反码 The complement is all by itself

对于负数(100000001)In terms of original code,Inverse code is the inverse operation of the original code except for the sign bit(111111110),Complement code is the one's complement code+1运算即(111111111)

Write the code below to test

public static void main(String[] args) {
    
  byte[] a=new byte[10];
  a[0]=-127;
  System.out.println("a[0]:"+a[0]);
  int b=a[0] & 0xFF;
  System.out.println("b:"+b);
 }

得到的结果为:

a[0]:-127
b:129

Now analyze this result:

byte类型的a[0]的值为-127,The two's complement stored in the computer is :10000001,This complement is8位的,而int类型是32位的,所以a[0]作为inttype to outputjvmI made a replacement for it 111111111111111111111111 10000001(-127),Although the complement is converted,But the two's complement representation of the decimal number is the same.

In order to ensure the consistency of binary data,当byte要转化为int的时候,高的24位必然会补1,这样,其二进制补码其实已经不一致了,如果二进制被当作byte和int来解读,其10进制的值必然是不同的,因为符号位位置已经发生了变化,而&0xFF可以将高的24位置为0,低8位保持原样.

int b = a[0]&0xff; a[0]&0xff=1111111111111111111111111 10000001&11111111=000000000000000000000000 10000001 ,这个值就是129

所以最后显示的b的值为129

文章来源:
Java中的byte & 0xff到底有什么作用?
原文链接:https://blog.csdn.net/qq_37855749/article/details/115736609
But it seems to be deleted by the author
侵删

copyright notice
author[Oxy],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/328/202211242212271084.html

Random recommended