C UINT16如何搞定?

时间:2013-10-14 22:19:26

标签: c int uint16

我是C编程的新手,我正在测试一些代码,我收到并处理格式化如下的UDP数据包:

UINT16 port1
UINT16 port2

此测试的相应值为:

6005
5555

如果我打印整个数据包缓冲区,我会得到这样的结果:

u^W³^U><9e>^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变量?

3 个答案:

答案 0 :(得分:0)

系统上的

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);

答案 1 :(得分:0)

您要传递给整数的AddToLogsnprintf指针。所以你所看到的是整数的地址,而不是整数本身。

您需要取消引用指针 - 例如,在第一种方法中,在primaryPort的调用中,在AddToLog前面加上星号(*)。

正如@rileyberton所建议的那样,系统中unsigned int很可能是4个字节,即C99类型uint32_t。对于16位整数,请使用uint16_t。这些在stdint.h中定义。这些传统上称为“短整数”或“半整数”,需要%hu中的printf限定符或类似函数,而不仅仅是%u(代表unsigned int,其大小取决于目标机器。)

另外,正如@ igor-tandetnik建议的那样,您可能需要切换数据包中整数的字节顺序,例如,如果数据包使用网络顺序(big-endian)格式,并且您的目标计算机使用的很少 - endian格式。

答案 2 :(得分:0)

您声明primaryPortsecondaryPortunsigned short的指针。

但是当你从缓冲区的一部分中分配它们时,你已经取消引用了指针。您不需要pointers-to-unsigned-short。您只需要unsigned short

将其更改为:

unsigned short primaryPort = *((unsigned short*) &buffer[l]); 

unsigned short secondaryPort = *((unsigned short *) &buffer[l]); 

请注意在变量声明中删除*

如果您仍然遇到问题,则需要逐字节检查buffer,查找您期望的值。您可以预期6005将显示为十六进制17 7575 17,具体取决于您平台的endianness