在C中提取字节 [英] Extracting bytes in C

查看:105
本文介绍了在C中提取字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C编写程序。我要提取字节。 un8 extractbyte(int r,int pos)应该从数字r返回字节数pos。例如,我使用输入: 0x7788AABB 。输出应为:

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:


部件号0为BB

部件号1为AA

部件号2是88

部件号3是77

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

我被卡在程序,我在评论中加了问号。这些行不正确,我对如何使它感到困惑……我现在得到的输出在每个部分都是bb。

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; // ??
}


推荐答案

un8 extractbyte(un32 r, un8 pos)
{
    return (r >> (8 * pos)) & 0xFF;
}

这篇关于在C中提取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆