C语言 c 获取整数的第 n 个字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7787423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c get nth byte of integer
提问by Kamran224
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.
但我不知道如何获取整数的第 n 个字节。例如,1234 是 00000000 00000000 00000100 11010010 作为 32 位整数 我怎样才能得到所有这些字节?第一个是 210,第二个是 4,最后两个是 0。
回答by Vaughn Cato
int x = (number >> (8*n)) & 0xff;
where n is 0 for the first byte, 1 for the second byte, etc.
其中 n 为第一个字节为 0,第二个字节为 1,依此类推。
回答by Dmitri
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):
对于它们出现在内存中的任何顺序的第 (n+1) 个字节(这在像 x86 这样的小端机器上也是最低到最高的):
int x = ((unsigned char *)(&number))[n];
For the (n+1)th byte from least to most significant on big-endian machines:
对于 big-endian 机器上从最低到最高有效的第 (n+1) 个字节:
int x = ((unsigned char *)(&number))[sizeof(int) - 1 - n];
For the (n+1)th byte from least to most significant (any endian):
对于从最低到最高有效(任何字节序)的第 (n+1) 个字节:
int x = ((unsigned int)number >> (n << 3)) & 0xff;
Of course, these all assume that n< sizeof(int), and that numberis an int.
当然,这些都假设n< sizeof(int),那number就是int.
回答by akappa
int nth = (number >> (n * 8)) & 0xFF;
int nth = (number >> (n * 8)) & 0xFF;
Carry it into the lowest byte and take it in the "familiar" manner.
将其放入最低字节并以“熟悉”的方式取出。
回答by David Fletcher
If you are wanting a byte, wouldn't the better solution be:
如果你想要一个字节,更好的解决方案不是:
byte x = (byte)(number >> (8 * n));
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 & 0xffjust 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.
这样,您将返回并处理一个字节而不是一个 int,因此我们使用的内存更少,而且我们不必执行二进制和操作& 0xff只是为了将结果屏蔽为一个字节。我还看到提出问题的人在他们的示例中使用了 int ,但这并不正确。
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.
我知道很久以前就有人问过这个问题,但我刚刚遇到了这个问题,我认为无论如何这是一个更好的解决方案。

