Re: Convert short to byte array
On Saturday, 2 March 2013 09:46:21 UTC, Alain Ketterlin wrote:
porcelli.giuseppe@gmail.com writes:
how to convert this routine to C++ ?
private byte[] getByteFromShort(short x) {
byte[] a = new byte[2];
a[0] = (byte) (x & 0xff);
a[1] = (byte) ((x >> 8) & 0xff);
return a;
}
Other answers give you detailed (and important) information about a
(more or less) literal translation of this code. I'd like to add that I
would not even write a function for such a simple operation:
int8_t xbytes [] = { x, x>>8 };
The advantage of the function is that if you change the format,
you just have one function to change.
Of course, whether this is useful depends on what you are going to do
with the array (which will live on the stack of the "calling" context).
Dynamic allocation is not cheap, C++ has no garbage collection by
default, so it's better to avoid putting pressure on the allocator for
such minuscule pieces of data. If you are going to pass this "array"
around, you should prefer data structures that carry their own size. But
are you really going to pass around the two bytes of a short? In actual
code, I would probably use either x and x>>8, or two distinct variables.
How about a:
struct BytesForShort
{
unsigned char bytes[ sizeof(short) ];
};
In most cases, of course, this would be part of a larger set of
serialization routines, and the output would be via a non-const
reference argument.
Note also that 1) I've used int8_t to respect Java's signedness of
bytes, you could switch to uint8_t to have unsigned bytes;
I think that you'ld almost certainly want an unsigned type.
2) iirc,
these types are not guaranteed to exist;
They are not. But since the starting point was Java, we can
assume they do. Otherwise, I don't think you could implement
Java on the machine.
3) I didn't bother to zero out
bits that get truncated later (this applies to your Java code as well,
where both "&0xff" are absolutely useless), but this is valid only if
int8_t exists (otherwise, more care is needed, depending on the later
usage of these "bytes").
I've gotten used to using the `0xFF` to make my intentions
clear, even if it isn't (usually) necessary. The compiler will
turn it into a no-op if it isn't necessary.
--
James