一、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-tw/n/204435.html
微信掃一掃
支付寶掃一掃