简体   繁体   中英

Java hexadecimal

I have a message

static int[] message = {
        0x01, 0x10, 0x00,
        0x01, // port addres 01 - 08
        0x00, 0x01, 0x02,
        0x06, 0x00,
        0xA4, 0x21
};

I know the data are right, as of I'm writing them to COM port with RXTX, and I got right HW reaction

I know that 0x01 is 1 value, and sent really like 01 (which is two bits, quarter byte long)

When I need to adjust the message, is generating values like this right?

message[index] = 1 & 0xff

I see the output of this snippet, and it looks properly

for (int i = 0; i < 255; i++) {
    System.out.println(i & 0xff);
}

Is there any sheet you'd recommend me to read?
Is storing these numbers in int right, as we cannot use byte (-128, +127) for values up to <0x00, 0xFF> range

You probably want to use a ByteBuffer for what you need, and wrap it under a class.

I don't know your exact message format, but let's say for a moment this is 3 bytes of data and 1 byte of a port:

public final class Message
{
    private static final MESSAGE_SIZE = 4;
    private static final PORT_OFFSET=3;

    private final ByteBuffer buf;

    public Message()
    {
        buf = ByteBuffer.allocate(MESSAGE_SIZE);
    }

    public void setPort(final byte b)
    {
        buf.put(PORT_OFFSET, b);
    }

    // etc

    public byte[] getRaw()
    {
        return buf.array();
    }
}

You can even use ByteBuffer's hashCode() and equals() to compare messages, if you only ever use absolute get/put methods (otherwise quite a bit of gymnastic is in order).

I used this technique to read/write NRPE packets.

I know that 0x01 is 1 value, and sent really like 01 (which is two bits)

That's only true if you're doing something to make that happen. A Java int is a 32-bit value ( reference ). Just because the value doesn't require all of those bits doesn't mean they aren't sent, because you may need all of the bits for a different value. The size of what you're sending could be limited by how you're sending it, but given the other values you quote, you can be sure you're sending at least eight of the bits.

If you're using OutputStream#write , what gets sent will depend entirely on the concrete implementation. OutputStream is an abstract class defining semantics for writing to streams; it doesn't define the stream itself. A concrete subclass is required to actually define what gets written. A FileOutputStream and a ByteArrayOutputStream and a PipedOutputStream all output the data differently.

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