简体   繁体   中英

byte to int conversion & vice versa java

I am trying to convert a integer into byte and retrieving the integer back in my code.

code:

ByteArrayOutputStream barrayStream = null;
        DataOutputStream outputStream = null;
        try {
            initSequence();
            barrayStream = new ByteArrayOutputStream();
            outputStream = new DataOutputStream(barrayStream);
            outputStream.writeByte(4);
            outputStream.writeInt(xxxx);
            System.out.println("  String = "
                    + Arrays.toString(barrayStream.toByteArray()));
            handlePacket(barrayStream.toByteArray());
        }catch (IOException ie) {


ie.printStackTrace();
        } finally {
            try {
                if (barrayStream != null) {
                    barrayStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

void handlePacket(byte[] byteArray) throws IOException {

byte[] portArray = new byte[4];
System.arraycopy(byteArray, 1, portArray, 0, 4);
int byteToIntValue = 0;
        for (int i = 0; i < portArray.length; i++) {
            byteToIntValue = (byteToIntValue << 8) | portArray[i];
        }

        System.out.println("Port Number = " + byteToIntValue);
}

integer greater than 5120 gives the correct value while retrieving. But below 5119 gives the negative value Is there any specific reason for this. Any help will be appreciated.

output: for integer 5100 the output is [0, 0, 19, -20]

for integer greater than 5120 [0, 0, 20, 0]

Try this:

Byte to int:

Byte b = new Byte(rno[0]);
int i = b.intValue();

int to byte:

int i = 234;
byte b = (byte) i;

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

This is happening because a Java byte is a signed value, between -128 and 127. You're parsing the port number correctly. It's just when you use Arrays.toString that the bytes get displayed as signed numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM