【发布时间】:2013-10-14 22:19:26
【问题描述】:
我是 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 变量?
【问题讨论】:
-
如果你问的是C,为什么标签里有C++和C#?
-
很可能,在您的系统上
unsigned int实际上不是一个 16 位整数,而sizeof(unsigned int) != 2。而*(unsigned int) &buffer[l]没有任何意义(并且无法编译):您将指针转换为整数,然后尝试取消引用所述整数。 -
"另外,为什么我必须释放 char 字符串变量,但不需要释放 int 变量?"是否必须调用
free与变量的类型无关。 -
我有根据的猜测是,你想要这样的东西:
unit16_t primaryPort = ntohs(*(unit16_t*)&buffer[0]); unit16_t secondaryPort = ntohs(*(unit16_t*)&buffer[2]);