Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a uint16_t to char[2] to be sent over socket (unix)

I know that there are things out there roughly on this.. But my brains hurting and I can't find anything to make this work...

I am trying to send an 16 bit unsigned integer over a unix socket.. To do so I need to convert a uint16_t into two chars, then I need to read them in on the other end of the connection and convert it back into either an unsigned int or an uint16_t, at that point it doesn't matter if it uses 2bytes or 4bytes (I'm running 64bit, that's why I can't use unsigned int :)

I'm doing this in C btw

Thanks

like image 559
Michael Crook Avatar asked Nov 07 '12 22:11

Michael Crook


1 Answers

Why not just break it up into bytes with mask and shift?

 uint16_t value = 12345;
 char lo = value & 0xFF;
 char hi = value >> 8;

(edit)

On the other end, you assemble with the reverse:

 uint16_t value = lo | uint16_t(hi) << 8;

Off the top of my head, not sure if that cast is required.

like image 198
Steven Sudit Avatar answered Nov 09 '22 12:11

Steven Sudit