将数据从int复制到2个无符号字符

use*_*988 1 c int unsigned-char

如何将数据从int(int port1 = 52010)复制到一对无符号字符(unsigned char port2[2]?我不知道如何处理除法.

unw*_*ind 5

您通常使用遮罩和移位.

const unsigned short port = 52010;
uint8_t port2[2];
Run Code Online (Sandbox Code Playgroud)

大端:

port2[0] = port >> 8;
port2[1] = port & 255;
Run Code Online (Sandbox Code Playgroud)

小端:

port2[0] = port & 255;
port2[1] = port >> 8;
Run Code Online (Sandbox Code Playgroud)

对于像IP网络中使用的端口号这样的东西,你通常会转到所谓的"网络字节顺序"(又名"big-endian"),并且有一个特殊的宏来执行此操作:

const unsigned short port_n = ntohs(port);
Run Code Online (Sandbox Code Playgroud)

请注意,这会将端口号保留为a unsigned short,同时在必要时交换字节.