qfedu-network-advanced-level/day2/test2.c

34 lines
893 B
C
Raw Permalink Normal View History

2023-09-05 20:54:17 +08:00
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[])
{
unsigned int data = 0x01020304;
printf("主机字节序: ");
for (int i = 0; i < sizeof(unsigned int); i++) {
unsigned char byte = (data >> (i * 8)) & 0xFF;
printf("%02x", byte);
}
printf("\n");
// 转成网络字节序(小端转大端)
uint32_t data2 = htonl(data);
printf("网络字节序: ");
for (int i = 0; i < sizeof(uint32_t); i++) {
unsigned char byte = (data2 >> (i * 8)) & 0xFF;
printf("%02x", byte);
}
printf("\n");
// 将网络字节序转为主机字节序
uint32_t data3 = ntohl(data2);
printf("转换后主机字节序: ");
for (int i = 0; i < sizeof(uint32_t); i++) {
unsigned char byte = (data3 >> (i * 8)) & 0xFF;
printf("%02x", byte);
}
printf("\n");
return 0;
}