任何人都可以解释为什么以下不编译?
byte b = 255 << 1
Run Code Online (Sandbox Code Playgroud)
错误:
常量值'510'无法转换为'字节'
我期待二进制中的以下内容:
1111 1110
Run Code Online (Sandbox Code Playgroud)
类型转换困扰了我.
说我有这样的功能:
inline int shift( int what, int bitCount )
{
return what >> bitCount;
}
Run Code Online (Sandbox Code Playgroud)
它将从不同的站点调用,每次bitCount都是非负的并且在位数内int.我特别关注bitCount等于零的呼叫- 它会正常工作吗?
还有可能编译器在编译其调用站点时看到函数的整个代码会减少bitCount等于零的调用到无操作吗?
我对这个问题很感兴趣
交错位明显的方式
(来自http://graphics.stanford.edu/~seander/bithacks.html)
Run Code Online (Sandbox Code Playgroud)unsigned short x; // Interleave bits of x and y, so that all of the unsigned short y; // bits of x are in the even positions and y in the odd; unsigned int z = 0; // z gets the resulting Morton Number. for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed... { z |= (x & 1U << i) << i | (y & 1U << …
好吧,我尝试查找>>或者移动意味着什么,但是这个网站解释了它:http://www.janeg.ca/scjp/oper/shift.html
那么有人可以解释它就像他们正在和一个孩子说话吗?
在http://tour.golang.org/#14上,他们展示了一个数字1移位64位的例子.这当然会导致溢出,但随后减去1并且一切都很好.一半表达式如何导致失败,而整个表达式整体工作正常?
思考:
我认为将无符号设置为大于允许数量的数字是导致爆炸的原因.看起来内存在表达式的右侧比在左侧更松散地分配?这是真的?
我正在使用别人的代码,该代码是用较旧的编译器编写的,它将特殊BOOL类型unsigned int映射到a,但在我的编译器中它映射到true bool.在他的代码一些地方他使用的按位移位运算符<<的bool类型,这是我以前从未见过和我的编译器让我感到惊讶时,它并没有抱怨.
这是有效的C++吗?是bool自动升级为int或uint?
我看到了这个相关的问题,它提供了另一个问题的清晰度,但它并没有解决转变运算符.
请考虑以下代码:
UInt32 val = 1;
UInt32 shift31 = val << 31; // shift31 == 0x80000000
UInt32 shift32 = val << 32; // shift32 == 0x00000001
UInt32 shift33 = val << 33; // shift33 == 0x00000002
UInt32 shift33a = (UInt32)((UInt64)val << 33); // shift33a == 0x00000000
Run Code Online (Sandbox Code Playgroud)
它不会生成警告(关于使用大于32的班次),因此它必须是预期的行为.
实际上被放到生成的程序集中的代码(或者至少是Reflector对代码的解释)是
uint val = 1;
uint shift31 = val << 0x1f;
uint shift32 = val;
uint shift33 = val << 1;
uint shift33a = val << 0x21;
Run Code Online (Sandbox Code Playgroud)
IL(再次,使用Reflector)是
L_0000: nop
L_0001: ldc.i4.1
L_0002: stloc.0 …Run Code Online (Sandbox Code Playgroud) 使用Shift运算符而不是使用除法和乘法的目的是什么?
使用移位运营商还有其他好处吗?
应该在哪里尝试使用移位运算符?
我试图找到有关<<和>>运算符如何处理整数的确切信息,但我找不到一个明确的答案(文档在这方面并不是那么好).
语义的两个部分对我来说并不清楚.首先,哪些位"移入"?
0b1110_1010u8 << 4 == 0b1010_0000u8)移入,或0b1110_1010u8 << 4 == 0b1010_1110u8),或此外,移位如何使用有符号整数?符号位是否也参与了班次?或者这是未指定的?
我的问题是
np.array([2**31], dtype=np.uint32) >> 32
Run Code Online (Sandbox Code Playgroud)
不返回0,而是返回array([2147483648], dtype=uint32)。情况也是如此
np.right_shift(np.array([2**31], dtype=np.uint32), 32)
Run Code Online (Sandbox Code Playgroud)
(所以我相信这只是>>实现方式)。
有趣的是,所有这些替代方案似乎都能按预期工作,并返回了以下内容0:
print(
2**31 >> 32,
np.uint32(2**31) >> 32,
np.array(2**31, dtype=np.uint32) >> 32,
np.right_shift(2**31, 32),
np.right_shift([2**31], 32),
np.right_shift(np.uint32(2**31), 32),
np.right_shift(np.array(2**31, dtype=np.uint32), 32),
)
Run Code Online (Sandbox Code Playgroud)
特别是,代表2147483648和的Numpy数组之间有什么区别[2147483648]?
我已经在JavaScript(为什么<< << 32在JavaScript中不会导致0?)和C ++(右移运算符(1 >> 32)的奇怪行为,为什么'int >> 32`并不总是为零?)中看到这个问题。,但尚未在Python / Numpy中使用。实际上,Python和Numpy文档似乎都没有记录这种行为: