Extracting bytes in C

2020-04-01 05:57发布

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: 0x7788AABB. Output then should be:

Part number 0 is BB
Part number 1 is AA
Part number 2 is 88
Part number 3 is 77

I am stuck at the last part of the program, where I have put the question marks in the comments. Those lines aren't right and I am confused in how I should make it work... The output I get now is bb at every part. I am pretty new at C by the way.

#include <stdio.h>
#include <stdlib.h>

typedef unsigned int  un32;
typedef unsigned char  un8;

un8  extractbyte  (un32  r, un8  pos);

int main ()
{
    un32  number;
    un8     k;

    printf("Enter a number:\n");
    scanf("%x",&number); 

    for (k=0; k<=3;k++)
        printf ("Part number %d is:  %x \n", k , extractbyte(number, k) );

    return 0;
}

un8 extractbyte  (un32  r ,  un8  pos)
{
    un32  mask;
    un32 size = pos*8;
    un32; // ??
    un8; // ??

    return (un8)  r; // ??
}

标签: c byte extract
3条回答
一纸荒年 Trace。
2楼-- · 2020-04-01 06:40
#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;
}
查看更多
小情绪 Triste *
3楼-- · 2020-04-01 06:45

I would make your extractbyte function something like this.

int extractbyte(int n, int pos)
{
    return (n >> (pos * 8)) & 0xff;
}
查看更多
神经病院院长
4楼-- · 2020-04-01 06:57
un8 extractbyte(un32 r, un8 pos)
{
    return (r >> (8 * pos)) & 0xFF;
}
查看更多
登录 后发表回答