How to cast uint8* to short*

Hi,

I send data over the network with a function like this:

SendData(void* data, int size);

where data is a 'signed short*'
On the other side I get the data with:

DataArrived(uint8_t* data, size_t size)

Here I need to cast the data to the original 'signed short*' because I have to insert it into a vector<signed short>

Is there a way to do the casting efficently?

Daniele.
Integral types can be casted one to another with not many problems.
Just notice that if the unsigned number has a high value, you will get a negative number in the signed version of the same type
...
You're directly casting an integer to a buffer that will be sent over a network? That's one of the worst things you could possibly do.
You're supposed to first manually convert it to avoid endianness problems:
1
2
3
4
5
char buffer[]={
    unsigned(n)&0xFF, //when twiddling bits, it's usually better to use unsigned types
    unsigned(n)>>8
}
SendData(buffer,2);

Then when you receive the data on the other end, you perform the inverse operation.
@helios

No no, I'm not casting before sending data over the network.
The Network library I use retreives data like uint8_t* while I have sent a buffer of 'signed short*'.

For now I'm using the direct casting and it works:

1
2
3
4
5
6
7
8
9
typedef signed short data_type;

DataArrived(uint8_t* data, size_t size)
{
  data_type* mybuffer = (data_type*)data;
  size /= sizeof(data_type);

  .... save mybuffer into vector<data_type>
}


Could be correct?

Thanks,
Daniele.
Post the context that calls SendData().
1
2
3
4
5
6
7
8
9
10
int WaveStream::SendPacket(sample_type* packet, uint16_t items)
{

  void* payload = static_cast<void*>(packet);
  size_t size = (sizeof(sample_type) * items);
  
  last_error_ = session_.SendPacket(payload, size);

  return last_error_;
}


Ops..in your previous post you talk about the cast from sample_type to void*?
If so then, yes, I'm casting before sending.

The prototype of session_.SendPacket is

SendPacket(void* payload, size_t size);

Daniele.
Yes, that's exactly what you shouldn't do.

http://en.wikipedia.org/wiki/Endianness
Ok, I know.

But the library I use (it is an rtp library) take care of endianness so, recasting the received packet should be ok, doesn't it?

Daniele.
Topic archived. No new replies allowed.