c get nth byte of integer

前端 未结 4 681
长情又很酷
长情又很酷 2020-11-28 06:01

I know you can get the first byte by using

int x = number & ((1<<8)-1);

or

int x = number & 0xFF;

4条回答
  •  时光说笑
    2020-11-28 06:13

    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.

提交回复
热议问题