[英]Strange bitwise operation on a 16-bit integer
i'm looking at ac 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. 在标准ANSI C rand()返回[0,32767]中的整数的同时,我非常感谢您帮助理解分母是哪种归一化因子,因为带符号整数为16位,并且表达式进行31位移位。
Thank you very much for your attention Best regards 非常感谢您的关注最好的问候
rand
does not return an integer in [0,32767] in "ANSI C". rand
在“ ANSI C”的[0,32767]中不返回整数。 §7.20.2: §7.20.2:
The
rand
function computes a sequence of pseudo-random integers in the range0
toRAND_MAX
.rand
函数计算范围为0
到RAND_MAX
的伪随机整数序列。
It seems likely that whoever wrote that macro was working on a platform on which RAND_MAX
was 2147483647. 似乎无论谁编写该宏,都可能在
RAND_MAX
为2147483647的平台上工作。
You also seem to be confused about signed integers. 您似乎也对带符号整数感到困惑。
int
must be at least 16 bits wide, but it is often wider. int
必须至少为 16位宽,但通常更宽。
#define random ( (float) rand() / (float) ((1 << 31) -1) )
in a system with 16-bit int
, this macro is undefined behavior because of 1 << 31
expression ( 1
is of int
type). 在具有16位
int
的系统中,由于1 << 31
表达式( 1
是int
类型),因此此宏是未定义的行为。
(C99, 6.5.7p3) "If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand , the behavior is undefined."
(C99,6.5.7p3)“如果右操作数的值为负或大于或等于提升后的左操作数的宽度 ,则行为不确定。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.