如何收拾在一个C程序unsigned char变量的十六进制值? [英] How to pack a hexadecimal value in an unsigned char variable in a C program?

查看:483
本文介绍了如何收拾在一个C程序unsigned char变量的十六进制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十六进制值F69CF355B6231FDBD91EB1E22B61EA1F在一个字符串,我在这样的unsigned char变量硬编码值用在我的计划该值:
unsigned char型A [] = {0xF6,为0x9c,0xF3,将0x55,0xB6,0x23,0x1F的,0xDB,0xD9,0X1E,0xB1,0xE2,0x2B访问,0x61,0xEA,为0x1F};
有没有通过,我可以从一个字符串取值,并把它变成一个无符号的变量在十六进制格式由包装呢?

任何函数或任何其他方法
解决方案

 的#include<&stdio.h中GT;
#包括LT&;&文件ctype.h GT;INT hctoi(为const char高){
    如果(ISDIGIT(H))
        回^ h - '0';
    其他
        返回TOUPPER(H) - 'A'+ 10;
}诠释主要(无效){
    为const char CDATA [] =F69CF355B6231FDBD91EB1E22B61EA1F;
    无符号字符UDATA [(的sizeof(CDATA)-1)/ 2];
    为const char * p;
    无符号字符*了;    为(P = CDATA,同比增长= UDATA; * P,P + = 2,++以上){
        *向上= hctoi(第[0])* 16 + hctoi(第[1]);
    }    {//检查code
        INT I;
        对于(i = 0; I<的sizeof(UDATA); ++ I)
            的printf(%02X,UDATA [I]);
    }
    返回0;
}

I have a hexadecimal value "F69CF355B6231FDBD91EB1E22B61EA1F" in a string and I am using this value in my program by hardcoding the value in an unsigned char variable like this: unsigned char a[] = { 0xF6 ,0x9C ,0xF3 ,0x55 ,0xB6 ,0x23 ,0x1F ,0xDB ,0xD9 ,0x1E ,0xB1 ,0xE2 ,0x2B ,0x61 ,0xEA ,0x1F}; Is there any function or any other method by which I can take the value from a string and put it into an unsigned variable in the hexadecimal format by packing it?

解决方案

#include <stdio.h>
#include <ctype.h>

int hctoi(const char h){
    if(isdigit(h))
        return h - '0';
    else
        return toupper(h) - 'A' + 10;
}

int main(void){
    const char cdata[]="F69CF355B6231FDBD91EB1E22B61EA1F";
    unsigned char udata[(sizeof(cdata)-1)/2];
    const char *p;
    unsigned char *up;

    for(p=cdata,up=udata;*p;p+=2,++up){
        *up = hctoi(p[0])*16 + hctoi(p[1]);
    }

    {   //check code
        int i;
        for(i=0;i<sizeof(udata);++i)
            printf("%02X", udata[i]);
    }
    return 0;
}

这篇关于如何收拾在一个C程序unsigned char变量的十六进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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