Re: Convert short to byte array
On 2/28/2013 4:43 PM, Nobody wrote:
On Thu, 28 Feb 2013 11:21:55 -0800, porcelli.giuseppe wrote:
Sorry for this stupid question by I am very new to C++
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;
}
Bare (C-style) arrays can't be returned by value. You need to use
e.g. std::array (std::tr1::array prior to C++11), e.g.:
std::array<uint8_t, 2> getByteFromShort(uint16_t x) {
std::array<uint8_t, 2> a;
a[0] = (uint8_t) (x & 0xff);
a[1] = (uint8_t) ((x >> 8) & 0xff);
return a;
}
If you really want to use a bare array, have the caller pass it in:
void getByteFromShort(uint16_t x, uint8_t a[2]) {
To the OP: this is a bit dangerous. The second argument is an address
of a 'uint8_t' value, but there is no guarantee that it points to an
array of two such values (so the index 1 can be used), and there is no
way for the compiler to verify that. I would probably recommend passing
this array by reference:
void getByteFromShort(uint16_t x, uint8_t (&a)[2]) {
a[0] = (uint8_t) (x & 0xff);
a[1] = (uint8_t) ((x >> 8) & 0xff);
}
[..]
V
--
I do not respond to top-posted replies, please don't ask