簡體   English   中英

在C中將ascii char []轉換為十六進制char []

[英]Convert ascii char[] to hexadecimal char[] in C

我試圖將ASCII中的char []轉換為十六進制的char []。

像這樣的東西:

你好 - > 68656C6C6F

我想通過鍵盤讀取字符串。 它必須是16個字符長。

這是我的代碼。 我不知道該怎么做。 我讀了關於strol但我認為它只是將str數轉換為int hex ...

#include <stdio.h>
main()
{
    int i = 0;
    char word[17];

    printf("Intro word:");

    fgets(word, 16, stdin);
    word[16] = '\0';
    for(i = 0; i<16; i++){
        printf("%c",word[i]);
    }
 }

我正在使用fgets,因為我讀的比fgets好,但我可以在必要時更改它。

與此相關,我試圖轉換uint8_t數組中讀取的字符串,將每個2字節連接在一起以獲取十六進制數。

我有這個功能,我在arduino中使用了很多,所以我認為它應該在正常的C程序中工作沒有問題。

uint8_t* hex_decode(char *in, size_t len, uint8_t *out)
{
    unsigned int i, t, hn, ln;

    for (t = 0,i = 0; i < len; i+=2,++t) {

            hn = in[i] > '9' ? (in[i]|32) - 'a' + 10 : in[i] - '0';
            ln = in[i+1] > '9' ? (in[i+1]|32) - 'a' + 10 : in[i+1] - '0';

            out[t] = (hn << 4 ) | ln;
            printf("%s",out[t]);
    }
    return out;

}

但是,每當我在代碼中調用該函數時,我都會遇到分段錯誤。

將此代碼添加到第一個答案的代碼中:

    uint8_t* out;
    hex_decode(key_DM, sizeof(out_key), out);

我試圖傳遞所有必要的參數並輸出我需要的數組,但它失敗了......

#include <stdio.h>
#include <string.h>

int main(void){
    char word[17], outword[33];//17:16+1, 33:16*2+1
    int i, len;

    printf("Intro word:");
    fgets(word, sizeof(word), stdin);
    len = strlen(word);
    if(word[len-1]=='\n')
        word[--len] = '\0';

    for(i = 0; i<len; i++){
        sprintf(outword+i*2, "%02X", word[i]);
    }
    printf("%s\n", outword);
    return 0;
}

替換這個

printf("%c",word[i]);

通過

printf("%02X",word[i]);

使用%02X格式參數:

printf("%02X",word[i]);

更多信息可以在這里找到: http//www.cplusplus.com/reference/cstdio/printf/

void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
    int i;

    for(i = 0; i < (len / 2); i++)
    {

        *(hex_ptr+i)   = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) :  (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
        *(hex_ptr+i)  |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') :  (*(ascii_ptr+(2*i)+1) - 'A' + 10);

    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM