C UINT16 How to get it right?

大憨熊 提交于 2019-12-01 14:13:42

You are passing to AddToLog and snprintf pointers to the integers. So what you're seeing are the addresses of the integers, not the integers themselves.

You need to dereference your pointers -- for example, put an asterisk (*) in front of primaryPort in your calls to AddToLog in your first approach.

As @rileyberton suggests, most likely unsigned int is 4 bytes on your system, which is the C99 type uint32_t. For a 16-bit integer, use uint16_t. These are defined in stdint.h. These are traditionally called "short integers" or "half integers" and require the %hu qualifier in printf or similar functions, rather than just %u (which stands for unsigned int, whose size depends on the target machine.)

Also, as @igor-tandetnik suggests, you may need to switch the byte order of the integers in your packet, if for example the packet is using network order (big-endian) format and your target machine is using little-endian format.

unsigned int on your system is likely 4 bytes (uint32_t). You can use unsigned int here if you mask out the values in the correct endianess, or simply use a short.

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

You declared primaryPort and secondaryPort to be pointers to unsigned short.

But when you assign them values from a section of buffer, you already de-referenced the pointer. You don't need pointers-to-unsigned-short. You just need an unsigned short.

Change it to:

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

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

Note the removal of a * in the variable declarations.

If you're still having problems, you'll need to examine buffer byte-by-byte, looking for the value you expect. You can expect that 6005 will show up as either hex 17 75 or 75 17, depending on your platform's endianness.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!