本文介绍了Endian检查宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大家好, 我试着写一个宏来检查系统是大端还是小端 但没有成功。不要误会我的意思,我写一个函数没问题,或者说b $ ba一个班轮就可以做到这一点,但我试图在一个_macro_中做这个没有 副作用(无全局变量声明)。我怀疑这不是 可能。 有人在乎证明我错了吗? - Guillaume Dargaud http://www.gdargaud.net/ 解决方案 #include< stdio.h> #define ENDIAN(){\ volatile unsigned long ul = 1; \ volatile unsigned char * p; \ p =(volatile unsigned char *)& ul; \ if(* p == 1)\ puts(Little endian。); \ else if(*( p +(sizeof(unsigned long)-1))== 1)\ puts(Big endian。); \ else puts(" ;未知的endian。"); \ } int main(无效){ ENDIAN(); 返回0; } 在C99中你可以使用复合文字来获得类似效果 你想要的东西[1]: (union {short n; char b [sizeof(short)];}){。n = 1} .b [0] Wrap,但是你想要它,在一个宏观中。 unsigned char可能更好用 一般而且这个代码有一千个问题,但没有 你正在做什么的一些细节,我不能建议更多健壮。 [1]我对使用 机器测试endian-ness的代码持谨慎态度它不是两个普遍接受的 替代品。 - Ben。 这是一个非常实用的解决方案,Santosh。我很惊讶没有人' 来警告你(volatile unsigned char *)& ul可能 包含陷阱表示并解除引用它导致UB,或者一些 这样的废话。 Hello all,I tried to write a macro to check if a system is big endian or little endianwith no success. Don''t get me wrong, I have no problem writing a function ora one liner to do that, but I was trying to do it in a _macro_ with noside-effect (no global variable declaration). I suspect this is notpossible. Anyone cares to prove me wrong ?--Guillaume Dargaud http://www.gdargaud.net/ 解决方案 #include <stdio.h> #define ENDIAN() { \volatile unsigned long ul = 1;\volatile unsigned char *p;\p = (volatile unsigned char *)&ul;\if (*p == 1)\puts("Little endian.");\else if (*(p+(sizeof(unsigned long)-1)) == 1)\puts("Big endian.");\else puts("Unknown endian.");\} int main(void) {ENDIAN();return 0;} In C99 you can use a compound literal to get something like the effectyou want[1]: (union {short n; char b[sizeof(short)];}){.n = 1}.b[0] Wrap, however you want it, in a macro. unsigned char might better ingeneral and there are a thousand issues with this code but withoutsome details of what you are doing, I can''t suggest anything morerobust. [1] I am wary of code that tests for endian-ness since I''ve usedmachines where it is neither of the two commonly acceptedalternatives. --Ben.That''s a remarkably practical solution, Santosh. I''m surprised no one''sbeen along yet to warn you that (volatile unsigned char *)&ul mightcontain a trap representation and dereferencing it cause UB, or somesuch nonsense. 这篇关于Endian检查宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 09:25