构造一个包含二进制数组的十六进制值的字符串
Construct a string who contain the hexValue of a binary array
我正在尝试从字节数组(libcrypto++)构造一个字符串,但我在"0"上遇到了问题,以便连接到c ++中的SQS
结果几乎是正确的,除了字符串末尾的一些"0"去。
std::string shaDigest(const std::string &key = "") {
byte out[64] = {0};
CryptoPP::SHA256().CalculateDigest(out, reinterpret_cast<const byte*>(key.c_str()), key.size());
std::stringstream ss;
std::string rep;
for (int i = 0; i < 64; i++) {
ss << std::hex << static_cast<int>(out[i]);
}
ss >> rep;
rep.erase(rep.begin()+64, rep.end());
return rep;
}
输出:
correct : c46268185ea2227958f810a84dce4ade54abc4f42a03153ef720150a40e2e07b
mine : c46268185ea2227958f810a84dce4ade54abc4f42a3153ef72015a40e2e07b00
^ ^
编辑:我正在尝试做与python中的hashlib.sha256('').hexdigest()
相同的操作。
如果这确实有效,这里是包含我的建议的解决方案。
std::string shaDigest(const std::string &key = "") {
std::array<byte, 64> out {};
CryptoPP::SHA256().CalculateDigest(out.data(), reinterpret_cast<const byte*>(key.c_str()), key.size());
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (byte b : out) {
ss << std::setw(2) << static_cast<int>(b);
}
// I don't think `.substr(0,64)` is needed here;
// hex ASCII form of 64-byte array should always have 128 characters
return ss.str();
}
您可以正确转换十六进制的字节,一旦字节值大于 15,它就会正常工作。但在下面,第一个六位数字是 0,默认情况下不打印。两个缺席的 0 分别表示 0x03
-> 3
和 0x0a
-> a
。
您应该使用 :
for (int i = 0; i < 64; i++) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(out[i]);
}
您需要设置整数的宽度,以便使用少于两个十六进制数字的数字进行适当的零填充。请注意,您需要在插入到流中的每个数字之前重新设置宽度。
例:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::hex << std::setfill('0');
for (int i=0; i<0x11; i++)
std::cout << std::setw(2) << i << "n";
}
输出:
$ g++ test.cc && ./a.out
00
01
02
03
04
05
06
07
08
09
0a
0b
0c
0d
0e
0f
10
供参考:
- http://en.cppreference.com/w/cpp/io/manip/setw
- http://en.cppreference.com/w/cpp/io/manip/setfill
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- 递归二进制搜索与字符串数组
- C++ 二进制数到整数值的数组
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 如何使用连接器 c++ 在 mySQL 表二进制(16) 字段中存储 c++ 字节数组?
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- 无法在二进制文件中存储动态数组
- 将文件信息(字符数组)嵌入到编译的二进制文件中
- 添加两个二进制数(整数数组)
- Python API用于解析包含数组格式的protobuf数据的二进制文件
- 将二进制读入十六进制字节数组
- 二进制字符数组转换为字符串流并从缓冲区弹出
- 从二进制文件读取到数组:前面的任意数字
- 将数组值 1 和 0 转换为二进制
- 写/读二维数组二进制文件c++
- 在c++中有效地管理数组二进制堆句柄