I'm doing an UDP connection, between a microcontroller and a computer. The framework I'm using is c++ based and has a function to send an UDP packet with the following prototype:
bool UdpConnection::send(const char *data, int length)
int length
is the number of bytes that the pointer contains.
But I'm doing some input reading using a function that returns a uint16_t
type.
I cannot change anything directly in those two functions.
Then I did the following:
UdpConnection udp;
uint16_t dummy = 256;
udp.send(reinterpret_cast<char*>(dummy),2);
But I'm a curious guy so I tried the following:
UdpConnection udp;
uint16_t dummy = 256;
udp.send((char*)dummy,2);
When I compile this last code I get:
error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
In my analysis both snippets do the same thing, why I get an error in the last one but not in the first?
EDIT:
The first snippet of code compiles but gives segmentation fault when the code runs. So neither code works.
EDIT 2:
An efficient and tested solution for the problem, but not an answer to the original question, is this:
union Shifter {
uint16_t b16;
char b8[2];
} static shifter;
shifter.b16 = 256;
udp.send(shifter.b8,2);
This solution is widely used, but it's not portable as it's dependent on CPU byte ordering, so do a test in your application before to be sure.
I would assume this is correct:
udp.send(reinterpret_cast<char*>(&dummy),2);
Note ampersand. Otherwise you are sending two byes from address 256, which are probably random (at best). This is microcontroller, so it might not crash. Second version should be:
udp.send((char*)&dummy,2);