i need some help improving the following code – there is a conversion between byte and int, that does not work in all cases – I need some feedback to find and solve possible issues involving byteToInt IntToByte conversion
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);
}
Use
(byte) ((start >> 8) & 0xFF);and(byte) (start & 0xFF);.Note though it will only help for ints lower than 2^16.
To recollect bytes to int, use
(lo & 0xFF) | ((hi & 0xff) << 8):&will widen thebyteto an int, making negative bytes positive ints; shift and|will recollect the value.