【发布时间】:2013-06-17 20:19:52
【问题描述】:
我有一个看起来像这样的二进制数:
00000000 00000000 00000011 00001101 = 781 整数值 = 整数名称“打包”
我如何能够在 java 中使用逐位将它们中的每一个提取为单独的整数值。像下面这样:
int a = (function) = 00000000;
int b = (function) = 00000000;
int c = (function) = 00000011;
int d = (function) = 00001101;
如果你能看到我在上面做什么..我希望前 8 个转换为一个整数,然后将下一个转换为第二个整数,依此类推.. 我认为你在 java 中使用位元来做到这一点,但我完全不确定。任何帮助表示赞赏。对不起,但我对这种事情完全陌生,真的需要帮助,谢谢!基本上 (function) 应该是这样的:
packed >> 5; (I know this isn't nearly right that is why i am needing help on this)...
2 天前为我回答了这个问题,它工作得很好,但现在它坏了......我不知道为什么......这是我用来做这个的方法:
public static int getNthByte(int n, int packed)
{
// shift the desired bits into the last 8 bits
int shifted = packed >> (8 * n);
// and now get those bits
int masked = 0x000000FF & shifted;
return masked;
}
但是当我输入这行代码时:我得到了这个答案:
int x = 781;
System.out.println(getNthByte(3, x)); (Which should give me 00001101, in integer value)
我打印以下内容:
0
为什么?昨天这对我来说很好......但我注意到当我这样做时:
System.out.println(getNthByte(5, x));
它给了我第三位:
3
这是正确的......
tl;dr 这个方法昨天运行良好,现在一切都搞砸了,我需要帮助修复它,或者可能是我的错误?我不知道.. 昨天我输入了 getNthByte(3,x),它给了我与 00001101 相关的正确整数值...
任何帮助表示赞赏..也许该方法有问题?还是只有我?
【问题讨论】:
-
尝试从函数中获取所有四个字节 (
n= 0, 1, 2 & 3)。您可能会发现自己从不同的角度数数。
标签: java binary extract bit-manipulation bit