#include <string>
#include <algorithm>
#include <iostream>
#include <climits>
#include <limits>
std::string tostr(unsigned long x)
{
// this will mask out the lower "byte" of the number
const unsigned char mask = std::numeric_limits<unsigned char>::max();
if (x == 0)
return std::string("0");
std::string res;
for (; x > 0; x >>= CHAR_BIT) {
res += (char) (x & mask);
}
std::reverse(res.begin(), res.end());
return res;
}
int main()
{
const size_t MAX = sizeof(unsigned long);
std::string s("abcd");
// std::string s("\226\226\226\226");
unsigned long res = 0;
for (size_t i=0; i < std::min(MAX, s.size()); ++i)
{
res <<= CHAR_BIT;
res += (unsigned char) s[i];
}
std::cout << std::hex << res << std::endl;
std::cout << tostr(res) << std::endl;
}
I2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y2xpbWl0cz4KI2luY2x1ZGUgPGxpbWl0cz4KCgpzdGQ6OnN0cmluZyB0b3N0cih1bnNpZ25lZCBsb25nIHgpCnsKICAvLyB0aGlzIHdpbGwgbWFzayBvdXQgdGhlIGxvd2VyICJieXRlIiBvZiB0aGUgbnVtYmVyCiAgY29uc3QgdW5zaWduZWQgY2hhciBtYXNrID0gc3RkOjpudW1lcmljX2xpbWl0czx1bnNpZ25lZCBjaGFyPjo6bWF4KCk7CiAgCiAgaWYgKHggPT0gMCkKICAgIHJldHVybiBzdGQ6OnN0cmluZygiMCIpOwogICAgCiAgc3RkOjpzdHJpbmcgcmVzOwogIGZvciAoOyB4ID4gMDsgeCA+Pj0gQ0hBUl9CSVQpIHsKICAgIHJlcyArPSAoY2hhcikgKHggJiBtYXNrKTsKICB9CiAgCiAgc3RkOjpyZXZlcnNlKHJlcy5iZWdpbigpLCByZXMuZW5kKCkpOwogIHJldHVybiByZXM7Cn0KCgppbnQgbWFpbigpCnsKICBjb25zdCBzaXplX3QgTUFYID0gc2l6ZW9mKHVuc2lnbmVkIGxvbmcpOwoKICBzdGQ6OnN0cmluZyBzKCJhYmN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