我需要改善以下代码的一些帮助-字节和整数之间存在转换,但并非在所有情况下都有效-我需要一些反馈来查找和解决涉及byteToInt的可能问题IntToByte转换
int start = 02;
int stepSize = 256;
int bytesLeftToRead =
// [0][1] encode a hex value as two bytes
// this part only works for [0] > 0 and [0] < 10 -- other restrictions?
response[0]*256 + Integer.parseInt(Integer.toHexString(response[1] + 256), 16);
while(bytesLeftToRead > 0){
// convert where to start from int to two bytes
cmdReadPD[2] = (byte) (start / 256);
cmdReadPD[3] = (byte) (start % 256);
if(stepSize > bytesLeftToRead){
stepSize = bytesLeftToRead;
}
// encode stepsize in two bytes
cmdReadPD[5] = (byte) (stepSize / 256);
cmdReadPD[6] = (byte) (stepSize % 256);
start += stepSize;
bytesLeftToRead -= stepSize;
read(cmdReadPD, stepSize);
}
最佳答案
使用(byte) ((start >> 8) & 0xFF);
和(byte) (start & 0xFF);
。
请注意,尽管它仅对小于2 ^ 16的整数有用。
要将字节重新收集为int,请使用(lo & 0xFF) | ((hi & 0xff) << 8)
:&
将byte
扩展为int,使负字节为正整数; shift和|
将重新收集值。