class Solution {
public:
string toHex(int num) {
string ret;
if (num == 0) ret = "0";
else if (num > 0) {
ret = toHex1(num);
}
else {
// 得到一个 1 0000 0000 0000 0000 0000 0000 0000 0000的数
unsigned long long n = (unsigned long long ) pow(2,32) - 1;
// n就变成了无符号位的,二进制后32位与原来的负数一样的数
n = n & num;
ret = toHex1(num);
}
return ret.size() > 8?ret.substr(ret.size() - 8) : ret;
}
string toHex1(unsigned long long num) {
string ret;
string hex[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
while (num) {
int pos = num % 16;
num /= 16;
ret += hex[pos];
}
reverse(ret.begin(), ret.end());
return ret;
}
};
近期评论