Tacitus86 Tacitus86 - 4 years ago 135
Java Question

How to serialize a decimal value (double) to a uint32 in Java?

So far I've been using the following code to convert signed to unsigned values that I need to send as a byte array over UDP to an embedded system.

public static byte serializeShort(short a)
{
return ((byte) (a & 0xFF));
}

public static short serializeInt(int a)
{
return ((short) (a & 0xFFFF));
}

public static int serializeLong(long a)
{
return ((int) (a & 0xFFFFFFFF));
}


The issue with the long, is some values can be real values. The output of this method I put into a bytebuffer via put(), putInt(), or putShort().

Any idea on how to translate the signed to unsigned for a double type?

Specifically here is my problem:

I have a UINT32 value that is being populated. I'm filling in my byte buffer with either a java signed LONG or a java signed double. I used the 'serializeLong()' above for the longs and it works fine, but the doubles do not.

ByteBuffer buffer = ByteBuffer.allocate(SIZE);
if (value instanceof Long)
{
buffer.putInt(Util.serializeLong((Long) value));
} else
{
buffer.putInt(Util.serializeLong(Double.doubleToLongBits((Double) value)));
}

Answer Source

Instead of using a Double, you should be using a float and to get it into the uint32 space use: buffer.putInt((Float.floatToRawIntBits(Math.abs((Float) value))));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download