转换uint16_t到char [2]通过套接字发送(UNIX) [英] 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...
我想通过Unix套接字发送16位无符号整数。要做到这一点,我需要一个uint16_t转换成两个字符,然后我需要阅读他们在连接的另一端并将其转换回无论是进入一个unsigned int或uint16_t,在这一点上,如果它使用2字节或4字节不要紧(我运行64位,这就是为什么我不能使用unsigned int类型:)
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 :)
我用C顺便说一句这样
感谢
推荐答案
为什么不把它分解成具有屏蔽字节和移位?
Why not just break it up into bytes with mask and shift?
uint16_t value = 12345;
char lo = value & 0xFF;
char hi = value >> 8;
(编辑)
在另一端,你的反向组合:
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.
这篇关于转换uint16_t到char [2]通过套接字发送(UNIX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!