2

我正在编写一个程序,其中一个数字(10 位数字)存储在 16 位数字的第一部分,然后在末尾存储一个 6 位数字。

如何利用位移来实现我的目标?

4

3 回答 3

8

注意:我将“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-17T20:20:19.323 回答
2

使用<<左移运算符和|二元或运算符。

将这些值放在一起:

short n = (short)(oneNumber << 6 | otherNumber);

(这些值int由二元运算符转换为,因此您必须将结果转换为short。)

要拆分值:

int oneNumber = n >> 6;
int otherNumher = n && 0x3F;
于 2012-08-17T20:21:27.833 回答
0
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
于 2012-08-17T20:24:50.047 回答