簡體   English   中英

C ++:將char *中的十六進制解釋為uint8_t

[英]C++ : interpreting hex in a char* as uint8_t

我需要使用以下格式的char *並帶有一些十六進制值。

char *buf = new char(12);
buf[0] = 0x2;
buf[1] = 0x0;
buf[2] = 0x3;
buf[3] = 0x3;
buf[4] = 0x0;
buf[5] = 0x0;
buf[6] = 0x6;
buf[7] = 0x4;
buf[8] = 0x0;
buf[9] = 0x2;
buf[10] =0x0;
buf[11] =0x0;

當我嘗試以這種方式打印它們時-

std::string hex_string;
create_hex_str((uint8_t*)buf, 12, hex_string);
std::cout << hex_string;

打印功能的定義:

void create_hex_str(uint8_t *data, int len, std::string &tgt)
{
    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    ss << "\n";
    for (int i=0; i<len; i++)
    {
        ss << std::setw(2) << static_cast<unsigned>(data[i]) << " ";        
    }
    target = ss.str();
}

我得到完全不同的輸出:f0 a1 56 08 28 02 3c f6 40 f8 56 08

有人可以幫我嗎? 如果這是一個非常瑣碎的問題,我感到抱歉,但是我根本無法理解這里發生了什么。 我究竟做錯了什么? 而且我必須將字節數組表示為char *。

new char(12);

這將為單個字符分配內存,並使用值12對其進行初始化。使用[]分配數組:

new char[12];

但是只有在您確實需要動態分配時才使用new[] 如果只需要代碼塊中的數組,則使用自動數組:

char buf[12];

如果確實需要new[] ,請記住在完成后將其刪除(使用delete[] ,而不僅僅是delete )。 更好的是,使用RAII類型(例如std::stringstd::vector<char>為您管理陣列。

TL; DR: 單擊此處進行在線編譯和執行。

這是一個工作代碼。 您應該使用new char [12]而不是new char(12),但是在這種特殊情況下,您甚至不需要new。 前者將構造一個包含12個元素的數組,而后者僅調用一個元素的構造函數。

另外,請注意,您使用的是“ target”而不是“ tgt”,因此您實際上並未設置輸出參數。

#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

void create_hex_str(uint8_t *data, int len, std::string &tgt)
{
    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    ss << "\n";
    for (int i=0; i<len; i++)
    {
        ss << std::setw(2) << static_cast<unsigned>(data[i]) << " ";        
    }
    tgt = ss.str();
}

int main()
{
    /* char buf[] = {
        0x2,
        0x0,
        0x3,
        0x3,
        0x0,
        0x0,
        0x6,
        0x4,
        0x0,
        0x2,
        0x0,
        0x0
    }; */

    char *buf = new char[12];
    buf[0] = 0x2;
    buf[1] = 0x0;
    buf[2] = 0x3;
    buf[3] = 0x3;
    buf[4] = 0x0;
    buf[5] = 0x0;
    buf[6] = 0x6;
    buf[7] = 0x4;
    buf[8] = 0x0;
    buf[9] = 0x2;
    buf[10] =0x0;
    buf[11] =0x0;

    std::string hex_string;
    create_hex_str((uint8_t*)buf, 12, hex_string);
    std::cout << hex_string;
}

我使用以下命令構建了此代碼: g++ --std=c++11 main.cpp && ./a.out

輸出為: 02 00 03 03 00 00 06 04 00 02 00 00

暫無
暫無

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

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