zoukankan      html  css  js  c++  java
  • 主机字节序和网络字节序

    一、网络字节序

      网际协议使用大端字节序来传送多字节整数

    二、确定主机字节序

    #include <stdio.h>
    
    int main(int argc, char **argv) {
        union {
            short s;
            char c[sizeof(short)];
        };
        un.s = 0x0102;
        if (sizeof(short) == 2) {
            if (un.c[0] == 1 && un.c[1] == 2) {
                printf("big-endian
    ");
            } else if (un.c[0] == 2 && un.c[1] == 1) {
                printf("little-endian
    ");
            } else {
                printf("unknow
    ");
            }
        } else {
            printf("sizeof(short) = %d
    ", sizeof(short));
        }
       exit(0); }

    三、主机字节序和网络字节序的转换

    #include <netinet/in.h>
    uint16_t htons(uint16_t host16bitvalue); uint32_t htons(uint32_t host32bitvalue);
    均返回:网络字节序的值
    uint16_t ntohs(uint16_t net16bitvalue); uint32_t ntohl(uint32_t net32bitvalue);
    均返回:主机字节序的值

    注:h代表host,n代表network,s代表short,l代表long

     

  • 相关阅读:
    杂记
    [POI2015]PUS
    CF786B Legacy(线段树优化建图)
    SP11470 TTM
    [WC2010]重建计划
    [HNOI2014]世界树
    luogu P4842 城市旅行
    [SDOI2016]征途
    [APIO2014]序列分割
    上下界网络流构图证明
  • 原文地址:https://www.cnblogs.com/soldierback/p/10663300.html
Copyright © 2011-2022 走看看