16 位整数上的奇怪按位运算
我正在查看 ac 源文件,我发现了这个宏:
#define random ( (float) rand() / (float) ((1 << 31) -1) )
虽然在标准 ANSI C rand() 返回 [0,32767] 中的整数,但我真的很感谢您帮助我理解分母是哪种归一化因子,因为有符号整数为 16 位,表达式进行 31 位移位。
非常感谢您的关注 此致
i'm looking at a c source file and i found this macro:
#define random ( (float) rand() / (float) ((1 << 31) -1) )
while in standard ANSI C rand() returns an integer in [0,32767], i really appreciate an help to understand what kind of normalization factor is the denominator, because signed integer are 16 bit and the expression does a 31-bit shift.
Thank you very much for your attention
Best regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
rand
不会返回“ANSI C”中 [0,32767] 中的整数。 §7.20.2:似乎编写该宏的人正在
RAND_MAX
为 2147483647 的平台上工作。您似乎也对有符号整数感到困惑。
int
必须至少 16 位宽,但通常更宽。rand
does not return an integer in [0,32767] in "ANSI C". §7.20.2:It seems likely that whoever wrote that macro was working on a platform on which
RAND_MAX
was 2147483647.You also seem to be confused about signed integers.
int
must be at least 16 bits wide, but it is often wider.在 16 位
int
系统中,该宏是未定义的行为,因为1 << 31
表达式(1
为int
类型)。in a system with 16-bit
int
, this macro is undefined behavior because of1 << 31
expression (1
is ofint
type).