簡體   English   中英

Char數組轉換為十六進制字符串C ++

[英]Char array to hex string C++

我在char*之前搜索了hex字符串,但是發現實現在hex字符串的末尾添加了一些不存在的垃圾。 我收到了來自套接字的數據包,我需要將它們轉換為hex字符串以記錄日志(以空終止的緩沖區)。 有人可以建議我C++的良好實現嗎?

謝謝!

假設數據為char *。 使用std :: hex的工作示例:

for(int i=0; i<data_length; ++i)
    std::cout << std::hex << (int)data[i];

或者,如果您想將所有內容都保留在字符串中:

std::stringstream ss;
for(int i=0; i<data_length; ++i)
    ss << std::hex << (int)data[i];
std::string mystr = ss.str();

這里是一些東西:

char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];

    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}

最簡單的:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

上面的代碼段在字符串中提供了錯誤的字節順序,因此我對其進行了一些修復。

char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   'B','C','D','E','F'};

std::string byte_2_str(char* bytes, int size) {
  std::string str;
  for (int i = 0; i < size; ++i) {
    const char ch = bytes[i];
    str.append(&hex[(ch  & 0xF0) >> 4], 1);
    str.append(&hex[ch & 0xF], 1);
  }
  return str;
}

我在這里找到了一個很好的例子Display-char-as-Hexadecimal-String-in-C ++

  std::vector<char> randomBytes(n);
  file.read(&randomBytes[0], n);

  // Displaying bytes: method 1
  // --------------------------
  for (auto& el : randomBytes)
    std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
  std::cout << '\n';

  // Displaying bytes: method 2
  // --------------------------
  for (auto& el : randomBytes)
    printf("%02hhx", el);
  std::cout << '\n';
  return 0;

上面顯示的方法1可能是更C ++的方式:

轉換為無符號整數
使用std::hex將值表示為十六進制數字
使用<iomanip> std::setwstd::setfill進行格式化
請注意,您需要針對0xff屏蔽0xff以顯示最低有效字節:
(0xff & (unsigned int)el)

否則,如果設置了最高位,則強制轉換將導致將三個最高有效字節設置為ff

使用升壓:

#include <boost/algorithm/hex.hpp>

std::string s("tralalalala");
std::string result;
boost::algorithm::hex(s.begin(), s.end(), std::back_inserter(result));

您可以嘗試使用此代碼將字節從數據包轉換為以空值結尾的字符串,然后存儲為“ string”變量以進行處理。

const int buffer_size = 2048;
// variable for storing buffer as printable HEX string
char data[buffer_size*2];
// receive message from socket
int ret = recvfrom(sock, buffer, sizeofbuffer, 0, reinterpret_cast<SOCKADDR *>(&from), &size);
// bytes converting cycle
for (int i=0,j=0; i<ret; i++,j+=2){ 
    char res[2]; 
    itoa((buffer[i] & 0xFF), res, 16);
        if (res[1] == 0) {
            data[j] = 0x30; data[j+1] = res[0];
        }else {
            data[j] = res[0]; data[j + 1] = res[1];
        }
}
// Null-Terminating the string with converted buffer
data[(ret * 2)] = 0;

當我們發送帶有十六進制字節0x01020E0F的消息時,變量“ data”具有字符串為“ 01020e0f”的char數組。

您可以使用std :: hex

例如。

std::cout << std::hex << packet;

暫無
暫無

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

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