簡體   English   中英

十六進制字符串到無符號字符[]

[英]hex string to unsigned char[]

今天,我嘗試將十六進制字符串轉換為無符號char []

string test = "fe5f0c";
unsigned char* uchar= (unsigned char *)test.c_str();
cout << uchar << endl;

這導致了輸出

fe5f0c

hrmpf :-(.。所需的行為如下:

unsigned char caTest[2]; 
caTest[0] = (unsigned char)0xfe;
caTest[1] = (unsigned char)0x5f;
caTest[2] = (unsigned char)0x0c;
cout << caTest << endl;

打印不可讀的ASCII代碼。 通常,我在做錯事^^。 將不勝感激任何建議。

提前致謝

當然,您只需在解析后隔離您感興趣的位即可:

#include <string>
#include <cstdlib>
#include <iostream>

typedef unsigned char byte;

int main()
{
    std::string test = "40414243";
    unsigned long x = strtoul(test.c_str(), 0, 16);
    byte a[] = {byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x), 0};
    std::cout << a << std::endl;
}

請注意,我將輸入字符串更改為八位數字,因為否則數組將從值0開始,而operator<<會將其解釋為結尾,並且您將看不到任何內容。

"fe5f0c"是6個字節的字符串(7個包含空終止符)。 如果將其視為數組,則會看到:

char str[] = { 102, 101, 53, 102, 48, 99 };

但是你想要

unsigned char str[] = { 0xfe, 0x5f, 0x0c };

前者是“人類可讀”表示,而后者是“機器可讀”數字。 如果要在它們之間進行轉換,則需要使用類似於@Fred編寫的代碼來明確地進行轉換。

強制轉換(在大多數情況下)並不意味着轉換,您只是告訴編譯器信任您,並且它可以忘記它認為自己對所強制轉換的表達式的了解。

這是十六進制字符串文字的一種更簡單的方法:

unsigned char *uchar = "\xfe\x5f\x0c";

暫無
暫無

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

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