什么是CHAR_BIT? [英] What is CHAR_BIT?

查看:225
本文介绍了什么是CHAR_BIT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引述code为未经 HTTP分支计算整数绝对值(ABS) ://graphics.stanford.edu/~seander/bithacks.html

int v;           // we want to find the absolute value of v
unsigned int r;  // the result goes here 
int const mask = v >> sizeof(int) * CHAR_BIT - 1;

r = (v + mask) ^ mask;

专利的变化:

r = (v ^ mask) - mask;

什么是 CHAR_BIT 和如何使用它?

推荐答案

您应该知道,这$ C $,c取决于权bitshift的签署类型实现定义的行为。 GCC承诺总是给人理智行为(符号位扩展),但ISO C允许实施零填充高位。

You should be aware that this code depends on the implementation-defined behavior of right bitshift on signed types. gcc promises to always give the sane behavior (sign-bit-extension) but ISO C allows the implementation to zero-fill the upper bits.

解决这个问题的一种方式:

One way around this problem:

#ifdef HAVE_SIGN_EXTENDING_BITSHIFT
int const mask = v >> sizeof(int) * CHAR_BIT - 1;
#else
int const mask = -((unsigned)v >> sizeof(int) * CHAR_BIT - 1);
#endif

的Makefile 的config.h 等可以定义 HAVE_SIGN_EXTENDING_BITSHIFT 在构建时根据您的平台。

Your Makefile or config.h etc. can define HAVE_SIGN_EXTENDING_BITSHIFT at build time depending on your platform.

这篇关于什么是CHAR_BIT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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