資料轉換-16進位制字元

卢泽發表於2024-06-03

在openEuler(推薦)或Ubuntu或Windows(不推薦)中完成下面任務

在附件中的utils.h和utils.c中完成16進位制字元'0'-'9','A'-'F','a'-'f'與十六進位制資料0-15的轉換功能(10’):

int Hex2Char(unsigned int fromi,unsigned char * toc);

int Char2Hex(unsigned char fromc,unsigned int * toi);

並寫出測試程式碼測試上述函式(不能與下面程式碼一樣),比如:(10’)

`unsigned char  c;`
`Hex2Char(1, &c)`
`//結果:c = '1'`
`Hex2Char(15, &c)`
`//結果:c = 'F'`
`unsigned int i;`
`Char2Hex('1', &i);`
`//結果:i = 1`
`Char2Hex('F', &i);`

`//結果:i = 15`

提交程式碼(或程式碼連結)和執行結果

uitls.h


    #ifndef UTIL_H
    
    #define UTIL_H
    
    //char Hex2Char(int i);
    
    //int Char2Hex(char c);
    
    int Hex2Char(int fromi,char * toc);
    
    int Char2Hex(char fromc,int * toi);
    
    int Bitstr2ByteArr(char * bs,char * ba);
    
    int ByteArr2Bitstr(char * ba,char * bs);
    
    int Int2ByteArr(int i,char * ba);
    
    int ByteArr2Int(char * ba,int * i);
    
    #endif

utils.c

`#include<stdio.h>`
`#include"utils.h"`
`char Hstr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};`
`int Hex2Char(int fromi,char *toc)`
`{`
    `if(fromi>=0&&fromi<=9)`
    `{*toc= fromi+'0';}
    else if(fromi>=10&&fromi<=15)
    {*toc = fromi+'A'-10;}`
    `else`
    `{printf("error");}`
    `return 0;}`
`int Char2Hex(char fromc,int *toi)
{
        if(fromc>='0'&& fromc<='9')
        {*toi= fromc-'0';`
        `}`
        `else if(fromc>='A'&& fromc<='F')`
        `{*toi= fromc-'A'+10;}`
        `else`
        `{printf("error");}`
        `return 0;`

`}``



main.c

`'#include<stdio.h>`
`#include"utils.h"`
`int main(){`
  `int n1,n2;`
  `char c1,c2;`
  `printf("請輸入一個0~15的數:");`
  `scanf("%d",&n1);`
  `Hex2Char(n1,&c1);`
  `printf("對應的16進位制字元是%c\n",c1);`
  `printf("請輸入一個16進位制字元:");`
  `scanf("%s",&c2);`
  `Char2Hex(c2,&n2);`
  `printf("%c對應的數是%d\n",c2,n2);`
`}'`

執行截圖:

git

相關文章