C近拍的定义来确定big endian还是little endian机器? [英] C Macro definition to determine big endian or little endian machine?

查看:213
本文介绍了C近拍的定义来确定big endian还是little endian机器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个行宏定义来判断机器的字节顺序。我使用下面的code,但其转换为宏就太长了。

  unsigned char型test_endian(无效)
{
    INT test_var = 1;
    unsigned char型test_endian * =(无符号字符*)及test_var;    回报(test_endian [0] == NULL);
}


解决方案

code支持任意字节命令,随时可以投入一个名为 order32.h

 的#ifndef ORDER32_H
#定义ORDER32_H#包括LT&;&limits.h中GT;
#包括LT&;&stdint.h GT;#如果CHAR_BIT!= 8
#ERROR不支持字符大小
#万一枚举
{
    O32_LITTLE_ENDIAN = 0x03020100ul,
    O32_BIG_ENDIAN = 0x00010203ul,
    O32_PDP_ENDIAN = 0x01000302ul
};静态常量工会{unsigned char型字节[4]; uint32_t的价值; } o32_host_order =
    {{0,1,2,3}};#定义O32_HOST_ORDER(o32_host_order.value)#万一

您将通过

检查小尾数系统

  O32_HOST_ORDER == O32_LITTLE_ENDIAN

Is there a one line macro definition to determine the endianness of the machine. I am using the following code but converting it to macro would be too long.

unsigned char test_endian( void )
{
    int test_var = 1;
    unsigned char test_endian* = (unsigned char*)&test_var;

    return (test_endian[0] == NULL);
}

解决方案

Code supporting arbitrary byte orders, ready to be put into a file called order32.h:

#ifndef ORDER32_H
#define ORDER32_H

#include <limits.h>
#include <stdint.h>

#if CHAR_BIT != 8
#error "unsupported char size"
#endif

enum
{
    O32_LITTLE_ENDIAN = 0x03020100ul,
    O32_BIG_ENDIAN = 0x00010203ul,
    O32_PDP_ENDIAN = 0x01000302ul
};

static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
    { { 0, 1, 2, 3 } };

#define O32_HOST_ORDER (o32_host_order.value)

#endif

You would check for little endian systems via

O32_HOST_ORDER == O32_LITTLE_ENDIAN

这篇关于C近拍的定义来确定big endian还是little endian机器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆