windows 10 vs2019 C++
下面代码生成形如“ADBF0000"这样的16机制文本,但我总觉得太过繁琐。那么多变量+语句。
我实际上就是需要随机取一个0-65535的数转16进制,以”0000“结尾,应该一共(4字节?)不知道有其他简单点的?
int main()
{
srand((unsigned int)time(NULL));
unsigned char a[4] = {0};
a[0]=(unsigned char)rand();
a[1] = (unsigned char)rand();
char b[8];
ByteToHexStr((const unsigned char*)a, b, 4);
stringstream stream;
stream << b;
string bbb = stream.str();
string str1 = bbb.substr(0, 8);
std::cout << str1 << std::endl;
}
void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)
{
short i;
unsigned char highByte, lowByte;
for (i = 0; i < sourceLen; i++)
{
highByte = source[i] >> 4;
lowByte = source[i] & 0x0f;
highByte += 0x30;
if (highByte > 0x39)
dest[i * 2] = highByte + 0x07;
else
dest[i * 2] = highByte;
lowByte += 0x30;
if (lowByte > 0x39)
dest[i * 2 + 1] = lowByte + 0x07;
else
dest[i * 2 + 1] = lowByte;
}
return;
}