2

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);
}
3
  • What's Integer.parseInt(Integer.toHexString(response[1] + 256), 16) for in your code?
    – alf
    Jan 5, 2012 at 12:13
  • response[1] encodes the first two digits of a hex number - since byte can be negative, I have to add 256 - then I use toHexString to convert the int value to a hexString and use parseInt to get the integer value of that hex
    – Schifty
    Jan 5, 2012 at 12:20
  • that's way too elaborated. See my answer, ((response[0] & 0xFF) << 8) | (response[1] & 0xFF) will do just fine, be easier to understand, and way faster.
    – alf
    Jan 5, 2012 at 12:22

2 Answers 2

1

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 the byte to an int, making negative bytes positive ints; shift and | will recollect the value.

1
  • just noticed that you forgot some brackets! it is actually ((hi & 0xFF) << 8)
    – Schifty
    Jan 12, 2012 at 13:46
0

I would use ByteBuffer to read and write short (signed) or char (unsigned) values.

ByteBuffer response = ByteBuffer.allocate(8);// .order(ByteOrder.LITTLE_ENDIAN);  if you need to change it.
ByteBuffer cmdReadPD = ByteBuffer.allocate(8);

int reponseCode = response.getChar(0);

while(cmdReadPD.remaining() > 0){
    // convert where to start from int to two bytes
    cmdReadPD.setshort(2, (short) start);

    if(stepSize > bytesLeftToRead)
        stepSize = bytesLeftToRead;

    // encode stepsize in two bytes
    cmdReadPD.setshort(4, (short) stepSize);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.