C UINT16 How to get it right?

前端 未结 3 1238
一整个雨季
一整个雨季 2021-01-16 18:38

I\'m new on C programming and I\'m testing some code where I receive and process an UDP packet formatted as follow:

UINT16 port1
UINT16 port2
3条回答
  •  太阳男子
    2021-01-16 19:29

    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.

提交回复
热议问题