简体   繁体   中英

java unsigned byte to stream

I am making an application that works with serial port. The problem is that the device I am controlling receive unsigned bytes range and as I saw java only accepts signed bytes range.

I have googled how to send, but I only got how to receive unsigned bytes.

Thanks EDIT 2: Fix proposed by @durandal to my code to receive:

 public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE: {
                System.out.println("Datos disponibles");
                try {
                    int b;
                int disponibles = input.available();
                byte[] rawData = new byte[disponibles];
                int count = 0;
                while ((b = input.read()) != -1) {
                    if (count == disponibles - 1) {
                        break;
                    }
                    rawData[count] = (byte) b;
                    count++;

                    }
                    serial.serialDataReceived(bytesToHex(rawData), rawData);
                } catch (IOException ex) {
                    Logger.getLogger(PuertoSerie.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            break;
        }

A byte is just 8-bits. Java assumes it is signed by default but you can treat it as unsigned if you wish. A common way to handle this is to use an int value which can store 0 to 255.

// from unsigned byte
byte[] bytes = ...
int value = 255;
bytes[0] = (byte) value;

// to unsigned byte
int value2 = bytes[0] & 0xFF;
// value2 == 255

You're making things overly complicated over nothing . A byte is a byte, there are no signed/unsigned bytes, only bytes. There is a signed/unsigned interpretation of a byte, but thats an entirely different concept.

You receiving code is broken, it will stop reading when it receives the byte value 0xFF, treating it as end-of-stream:

                byte b;
                int disponibles = input.available();
                byte[] rawData = new byte[disponibles];
                int count = 0;
                while ((b = (byte) input.read()) != -1) {
                    if (count == disponibles - 1) {
                        break;
                    }
                    rawData[count] = b;
                    count++;
                }

The problem is the declaration of "b" as byte (it should be int, you absolutely need the return value of read() as an int!) and the cast of input.read() to byte before checking for the -1 value. You should instead cast the int when you put it into the array, not in the for.

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