我在C程序设计新和我测试一些代码,我接收和处理格式化为后续一个UDP包:C UINT16如何正确使用?
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);
我在做什么错?另外,为什么我必须释放一个字符串变量,但我不需要释放int变量?
如果您问的是C,为什么C++和C#中的标签? – n0rd
最有可能的是,在你的系统中'unsigned int'实际上不是一个16位整数,而'sizeof(unsigned int)!= 2'。并且'*(unsigned int)&buffer [l]'没有任何意义(也不能编译):你正在投射一个指向一个整数的指针,然后试图解引用这个整数。 –
“另外,为什么我必须释放char字符串变量,但是我不需要释放int变量?”无论你是否需要调用'free',都不是变量类型的问题。 –