A special usage of a number &0xFF in Java language

I saw a piece of code today, and there are some details that confuse me

// 将一个数字转为对应的16进制表示
public static String byteToHexString (byte b) {
    
    
		
		int v = b & 0xFF; //发生了自动类型提升
		
		String hv = Integer.toHexString(v);
		
		if (hv.length() < 2) {
    
    
			
			hv = "0" + hv;
			
		}
		
		return hv;
		
} 

int v = b & 0xFF;
Among them, this line of code is useless at first glance, making people think that it has no effect. In fact, it plays the role of ensuring the consistency of the complement of variable b.
We want to use the Integer API, so we need to convert byte to int , but such a conversion will obviously change the number of digits. After reading the summary of the big guys on the Internet, JAVA stores data in complement code. This step of operation (the part highlighted in red) is actuallyIn order to ensure that the complement does not change, to make it clear is that the value of the complement code in the previous 8 digits cannot be changed after the expansion, but in this case, if it is a negative number, the value will inevitably change after executing this line. The benefits of doing so what is it ? ?
Please see the figure below↓
The output after using this method
insert image description here
. If this method is not used, then↓
insert image description here
It is obvious that the purpose is to remove the high-order 1 of the negative complement code, so that we can observe the result data more intuitively, which also reflects The importance of computer underlying knowledge
This code mainly contains two knowledge points:

  1. bitwise AND operation
  2. java automatic type promotion

I understand both of these two, but I didn’t understand them together for a long time, which shows that I can’t use knowledge well and flexibly.


Combined with my findings in other places here, the & operation is essentially setting and resetting

Guess you like

Origin blog.csdn.net/qq_45689267/article/details/108896729