我正在写一个程序,其中一个数字(一个10位数字)存储在16位数字的第一部分,然后在最后存储一个6位数字。
我如何利用位移位来实现我的目标?
发布于 2012-08-18 04:20:19
注意:我将“16位数的第一部分”解释为"10个最低有效位“--因为位数学通常从右开始倒数。
short x = (short)(value & 1023); // the first 10 bits
short y = (short)((value >> 10) & 63); // the last 6 bits
并进行重新组合:
value = (short)(x | (y << 10));
发布于 2012-08-18 04:21:28
使用<<
左移运算符和|
二进制或运算符。
要将值放在一起,请执行以下操作:
short n = (short)(oneNumber << 6 | otherNumber);
(值由二元运算符转换为int
,因此您必须将结果转换为short
。)
拆分值的步骤:
int oneNumber = n >> 6;
int otherNumher = n && 0x3F;
发布于 2012-08-18 04:24:50
ushort result=0;
ushort a=100;
ushort b= 43;
result=((result|(a<<6))|b&63)
//shift a by 6 bits to empty 6 bits at end,and then OR it with result.Strip from b, any bit ahead of 6 th place and OR it with result.
数学上:
0000000000000000 = result
0000000001100100 = a
0000000000101011 = b
0001100100000000 = (a<<6)
0000000000000000|0001100100000000 = (result|(a<<6))=0001100100000000
0000000000101011|0000000000111111 = b&63 =0000000000101011
0001100100000000|0000000000101011 = ((result|(a<<6))|b&63)=0001100100101011
result=6443
https://stackoverflow.com/questions/12012634
复制相似问题