C UINT16如何搞定?
我是C编程的新手,我正在测试一些代码,我收到并处理格式化如下的UDP数据包:
UINT16 port1 UINT16 port2
此测试的相应值为:
6005 5555
如果我打印整个数据包缓冲区,我得到这样的东西:
u^W³^U>^D
所以我认为我只需要打破它并处理为16字节的unsigned int
。 所以我尝试过这样的事情:
int l = 0; unsigned int *primaryPort = *(unsigned int) &buffer[l]; AddToLog(logInfo, "PrimaryPort: %u\n", primaryPort); l += sizeof(primaryPort); unsigned int *secondaryPort = *(unsigned int) &buffer[l]; AddToLog(logInfo, "SecondaryPort: %u\n", secondaryPort); l += sizeof(secondaryPort);
但我得到8位数的错误数字。
我甚至尝试了另一种方法,如跟随,但也得到错误的数字。
int l = 0; unsigned char primaryPort[16]; snprintf(primaryPort, sizeof(primaryPort), "%u", &buffer[l]); AddToLog(logInfo, "PrimaryPort: %d\n", primaryPort); l += sizeof(primaryPort); unsigned char secondaryPort[16]; snprintf(secondaryPort, sizeof(secondaryPort), "%u", &buffer[l]); AddToLog(logInfo, "SecondaryPort: %d\n", secondaryPort); l += sizeof(secondaryPort);
我做错了什么? 另外,为什么我必须释放一个char字符串变量,但我不需要释放int变量?
您将传递给整数的AddToLog
和snprintf
指针。 所以你看到的是整数的地址,而不是整数本身。
您需要取消引用指针 – 例如,在第一种方法中,在调用AddToLog
在AddToLog
前放置一个星号(*)。
正如@rileyberton建议的那样,很可能unsigned int
在你的系统上是4个字节,这是C99类型uint32_t
。 对于16位整数,请使用uint16_t
。 这些在stdint.h
中定义。 这些传统上称为“短整数”或“半整数”,并且需要printf
或类似函数中的%hu
限定符,而不仅仅是%u
(表示unsigned int
,其大小取决于目标计算机。)
此外,正如@ igor-tandetnik建议的那样,您可能需要切换数据包中整数的字节顺序,例如,如果数据包使用网络顺序(big-endian)格式,并且目标计算机使用的是little-endian格式。
系统上的unsigned int可能是4个字节(uint32_t)。 如果您在正确的字节序中屏蔽了值,或者只是使用短消息,则可以在此使用unsigned int。
int l = 0; unsigned short *primaryPort = *(unsigned short) &buffer[l]; AddToLog(logInfo, "PrimaryPort: %u\n", primaryPort); l += sizeof(*primaryPort); unsigned short *secondaryPort = *(unsigned short) &buffer[l]; AddToLog(logInfo, "SecondaryPort: %u\n", secondaryPort); l += sizeof(*secondaryPort);
您声明primaryPort
和secondaryPort
是unsigned short
指针。
但是当您从缓冲区的一部分中为它们分配值时,您已经取消引用了指针。 你不需要pointers-to-unsigned-short
。 你只需要一个unsigned short
。
将其更改为:
unsigned short primaryPort = *((unsigned short*) &buffer[l]); unsigned short secondaryPort = *((unsigned short *) &buffer[l]);
注意在变量声明中删除a *
。
如果您仍然遇到问题,则需要逐个字节地检查buffer
,查找您期望的值。 您可以预期6005
将显示为hex17 75
或75 17
,具体取决于您的平台的字节顺序 。