int type is coerced to lower precision byte type

The company's project will conduct code compliance checks before it goes live. One of the rules that is easy to violate is "don't convert primitive types to lower precision". In the actual development process, many methods are used to process data, especially when doing During the shift operation, it is inevitable to convert the int type to the byte type. At this time, it is inevitable that the original type will be converted to a lower precision. There is no easy way, only by calling ByteArrayOutputStream and DataOutputStream to deal with it. Encapsulate the processing in a function. Then call the function when the type conversion is performed. The processing function is as follows:

public byte intToButeArray(int n) {
byte[] byteArray = null;
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(byteOut);
dataOut.writeInt(n);
byteArray = byteOut.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray[3];
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325256718&siteId=291194637