C 语言中的小技巧

~0与0xFFFFFFFF的区别

在写代码时,常常会用到掩码,对于32位的机器来说,如果要得到位全为1的掩码,就写成0xFFFFFFFF,64位的机器上要得到全为1的掩码,要写成0xFFFFFFFFFFFFFFFF,所以,如果直接写就会遇到移植性问题。

这时我们可以用 ~0 来代替上面的写法,这个在编译时自动根据当前机器的位数来生成代码,这样就便于移植了。


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License