c get nth byte of integer

前端 未结 4 664
长情又很酷
长情又很酷 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条回答
  •  Happy的楠姐
    2020-11-28 06:24

    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.

提交回复
热议问题