我的问题是从十六进制包计算十进制字符后出了什么问题,字符串中的字符在将它们添加到字符串后都有负值,你能不能看一下这段代码,我会非常高兴每一个解决方案你提供
#include <vector>
#include <iostream>
#include <string>
// this function in to calculating a sha1 hash in decimal
std::string sha1_bits(const std::string &calc_before) // <-- calc_before = sha1 hash
{
// the final string, which will be returned at the end of the function
std::string r = "";
// the hexCharset in right order
const std::string hexaDezimalCharset = "0123456789abcdef";
// some constants
const int hexMultiplier = 16, hexpair = 2, shaInBitChar = 20;
int tempNum = 0;
std::vector<std::string> storage;
// resize the storage vector to 20
// there will be 20 chars, out of 40 char hex sha1 hash
storage.resize(shaInBitChar);
for(int i = 0; i < storage.size(); i++)
{
storage.at(i).resize(hexpair);
}
// put them in 20 strings, each of them has to chars with is forming 1 char when decoding in dezimal
for(int i = 0; i < calc_before.size(); i++)
{
storage.at((i - (i % hexpair)) / hexpair).at(i % hexpair) = calc_before.at(i);
}
// Print the hex packages, just for debug
for(int i = 0; i < storage.size(); i++)
{
for(int p = 0; p < storage.at(i).size(); p++)
{
std::cout << storage.at(i).at(p);
}
std::cout << std::endl;
}
std::cout << std::endl;
// for all doubled hex packages ...
for(int i = 0; i < storage.size(); i++)
{
// the tempNum is the final decimal value decoded from hex package
tempNum = 0;
for(int q = 0; q < storage.at(i).size(); q++)
{
for(int p = 0; p < hexaDezimalCharset.size(); p++)
{
// if the char is found in the hexCharset ...
if(hexaDezimalCharset.at(p) == storage.at(i).at(q))
{
// and it's the first char in the package
if(q == 0)
{
// the index will be multiplied with 16 and added to tempNum
tempNum += p * hexMultiplier;
}
else if(q == 1) // if its the second one
{
// the index will just added to tempNum
tempNum += p;
}
break;
}
}
}
// the tempNum will be added to r, after it was converted to char format
r.push_back(char(tempNum));
}
return r;
}
int main()
{
std::string theReturnedString = sha1_bits("b37a4f2cc0624f1690f64606cf385945b2bec4ea");
// But some chars extracted from the returned string have negative values
// Everything i could figure out is that the Numbers are fine, which are forming and are stored in tempNum
// the numbers only get negative if the hex package from which it formed began with an character instead of a number
// at this point i notice that i'm quite unconcetrated and my english is getting a mess
// shortly:
// hex package (storage) --> decimal (tempNum) --> put at the end of the string ( r.at( x ) )
// "b3" --> 179 --> -77
// "7a" --> 122 --> 122
// "4f" --> 79 --> 79
// maybe to escape my bad description you should take this code, put it into your compiler or http://cpp.sh, check out what's happening and
for(int i = 0; i < theReturnedString.size(); i++)
{
std::cout << (int) theReturnedString.at(i) << std::endl;
}
return 0;
}