c 获取整数的第n个字节
我知道你可以使用
int x = number & ((1<<8)-1);
or
int x = number & 0xFF;
获取第一个字节,但我不知道如何获取整数的第 n 个字节。 例如,1234 为 32 位整数 00000000 00000000 00000100 11010010 我怎样才能获得所有这些字节?第一个是 210,第二个是 4,最后两个是 0。
I know you can get the first byte by using
int x = number & ((1<<8)-1);
or
int x = number & 0xFF;
But I don't know how to get the nth byte of an integer.
For example, 1234 is 00000000 00000000 00000100 11010010 as 32bit integer
How can I get all of those bytes? first one would be 210, second would be 4 and the last two would be 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其中 n 为 0 表示第一个字节,1 表示第二个字节,依此类推。
where n is 0 for the first byte, 1 for the second byte, etc.
对于第 (n+1) 个字节,无论它们在内存中出现的顺序如何(在 x86 等小端机器上也是从最低到最高有效的):
对于在 x86 等小端机器上从最低到最高有效的第 (n+1) 个字节big-endian 机器:
对于从最低有效到最高有效的第 (n+1) 个字节(任何 endian):
当然,这些都假设
n
n
n
n
n
sizeof(int)
,并且该number
是一个int
。For the (n+1)th byte in whatever order they appear in memory (which is also least- to most- significant on little-endian machines like x86):
For the (n+1)th byte from least to most significant on big-endian machines:
For the (n+1)th byte from least to most significant (any endian):
Of course, these all assume that
n
<sizeof(int)
, and thatnumber
is anint
.int nth = (数字>>(n * 8)) & 0xFF;
将其带入最低字节并以“熟悉”的方式获取。
int nth = (number >> (n * 8)) & 0xFF;
Carry it into the lowest byte and take it in the "familiar" manner.
如果您想要一个字节,不是更好的解决方案是:
byte x = (byte)(number >> (8 * n));
这样,您将返回并处理一个字节而不是一个 int,所以我们使用了更少的内存,并且我们不必进行二进制和操作
& 0xff
只是为了将结果屏蔽为一个字节。我还看到提出问题的人在他们的示例中使用了 int ,但这并不意味着它是正确的。我知道这个问题很久以前就被问过,但我刚刚遇到这个问题,我认为无论如何这是一个更好的解决方案。
If you are wanting a byte, wouldn't the better solution be:
byte x = (byte)(number >> (8 * n));
This way, you are returning and dealing with a byte instead of an int, so we are using less memory, and we don't have to do the binary and operation
& 0xff
just to mask the result down to a byte. I also saw that the person asking the question used an int in their example, but that doesn't make it right.I know this question was asked a long time ago, but I just ran into this problem, and I think that this is a better solution regardless.