Schifty
Schifty

Reputation: 635

Improve Byte Conversion in Java

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);
}

Upvotes: 2

Views: 153

Answers (2)

alf
alf

Reputation: 8513

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

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);

Upvotes: 0

Related Questions