一、C++Hex是什麼
C++Hex是一個全能的16進制操作工具庫,可以方便地進行對16進制數據的處理,包括16進制編解碼、16進制字符串轉化為二進制數據、十六進制數與其他進制數之間的轉換等。
在現代軟件開發中,十六進制數據的處理具有重要的作用,所以C++Hex這個工具庫有助於提高程序開發效率。
二、C++Hex主要功能
C++Hex庫中的主要功能如下:
1.將16進制字符串轉化為二進制數據
2.將二進制數據轉化為16進制字符串
3.將16進制字符串轉化為十進制數
4.將十進制數轉化為16進制字符串
5.將16進制字符串轉化為ASCII字符串
6.將ASCII字符串轉化為16進制字符串
7.計算校驗和
三、C++Hex使用示例
#include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> #include <iomanip> #include <ctype.h> using namespace std; //十六進制字符串轉化為二進制數據 vector<char> hexStrToBytes(const string& hexStr) { vector<char> bytes; for (size_t idx = 0; idx < hexStr.size(); idx += 2) { unsigned int byte; stringstream ss; ss << hex << hexStr.substr(idx, 2); ss >> byte; bytes.push_back(static_cast<char>(byte)); } return bytes; } //計算校驗和 unsigned char calcChecksum(const vector<char>& bytes) { unsigned char checksum = 0; for (auto byte : bytes) { checksum ^= static_cast<unsigned char>(byte); } return checksum; } //二進制數據轉化為十六進制字符串 string bytesToHexStr(const vector<char>& bytes) { std::stringstream ss; ss << hex; for (auto byte : bytes) { ss << setw(2) << setfill('0') << static_cast<unsigned int>(static_cast<unsigned char>(byte)); } return ss.str(); } int main(int argc, char* argv[]) { string hexStr = "16DAAD2F3C23"; vector<char> bytes = hexStrToBytes(hexStr); unsigned char checksum = calcChecksum(bytes); string checksumHexStr = bytesToHexStr({ checksum }); cout << "Hex string: " << hexStr << "\n"; cout << "Checksum: " << setw(2) << setfill('0') << static_cast<unsigned int>(checksum) << "\n"; cout << "Checksum (hex): " << checksumHexStr << "\n"; return 0; }
四、C++Hex的功能拓展
基於C++Hex庫的基礎上可以進行拓展,例如計算CRC校驗碼,將16進制數據轉化為其他進制的數值等操作。
主要的代碼修改如下:
//計算CRC校驗碼 unsigned short calcCrc(const vector<char>& bytes) { unsigned short crc = 0xFFFF; for (auto byte : bytes) { crc ^= static_cast<unsigned char>(byte); for (size_t bitIndex = 0; bitIndex < 8; bitIndex++) { crc = (crc & 0x0001) ? ((crc >> 1) ^ 0xA001) : (crc >> 1); } } return crc; } //將16進制字符串轉化為十六進制數 int hexToInt(const string& hexStr) { int num; stringstream ss; ss << hex << hexStr; ss >> num; return num; } //將十六進制數轉化為十進制數 int hexToDec(const string& hexStr) { return static_cast<int>(strtol(hexStr.c_str(), nullptr, 16)); } int main(int argc, char* argv[]) { string hexStr = "16DAAD2F3C23"; vector<char> bytes = hexStrToBytes(hexStr); unsigned char checksum = calcChecksum(bytes); string checksumHexStr = bytesToHexStr({ checksum }); unsigned short crc = calcCrc(bytes); int hexNum = hexToInt(hexStr); int decNum = hexToDec(hexStr); cout << "Hex string: " << hexStr << "\n"; cout << "Checksum: " << setw(2) << setfill('0') << static_cast<unsigned int>(checksum) << "\n"; cout << "Checksum (hex): " << checksumHexStr << "\n"; cout << "CRC: " << hex << setw(4) << setfill('0') << crc << "\n"; cout << "Hex num: " << hexNum << "\n"; cout << "Dec num: " << decNum << "\n"; return 0; }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/204435.html