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 };
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.
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; 2) iirc,
these types are not guaranteed to exist; 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").
-- Alain.