c get nth byte of integer

心已入冬 提交于 2019-11-26 09:07:53

问题


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.


回答1:


int x = (number >> (8*n)) & 0xff;

where n is 0 for the first byte, 1 for the second byte, etc.




回答2:


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):

int x = ((unsigned char *)(&number))[n];

For the (n+1)th byte from least to most significant on big-endian machines:

int x = ((unsigned char *)(&number))[sizeof(int) - 1 - n];

For the (n+1)th byte from least to most significant (any endian):

int x = ((unsigned int)number >> (n << 3)) & 0xff;

Of course, these all assume that n < sizeof(int), and that number is an int.




回答3:


int nth = (number >> (n * 8)) & 0xFF;

Carry it into the lowest byte and take it in the "familiar" manner.




回答4:


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.



来源:https://stackoverflow.com/questions/7787423/c-get-nth-byte-of-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!