Extracting bytes in C

后端 未结 3 2001
一个人的身影
一个人的身影 2021-01-16 19:15

I\'m making a program in C. I am to extract bytes. un8 extractbyte (int r, int pos) should return byte number pos from number r. As example, I use as input: <

相关标签:
3条回答
  • 2021-01-16 19:48

    I would make your extractbyte function something like this.

    int extractbyte(int n, int pos)
    {
        return (n >> (pos * 8)) & 0xff;
    }
    
    0 讨论(0)
  • 2021-01-16 19:53
    un8 extractbyte(un32 r, un8 pos)
    {
        return (r >> (8 * pos)) & 0xFF;
    }
    
    0 讨论(0)
  • 2021-01-16 19:57
    #include <stdio.h>
    
    char extractbyte(int number, int v) {
        char *x=(char *)&number;
        return x[3-v];
    }
    
    int main() {
    
        int n=0x7788aabb;
        int i;
        for (i=0; i<4; i++) {
            printf("%d) %x\n",i,(unsigned char)extractbyte(n,i));
        }
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题