记录下整型转换为32位二进制字符串的两种方式。
一、返回string 类型
char digits[] =
{
'0','1','2','3','4','5',
'6','7','8','9','a','b',
'c','d','e','f','g','h',
'i','j','k','l','m','n',
'o','p','q','r','s','t',
'u','v','w','x','y','z'
};
std::string ToBinaryString(int i)
{
char buf[32] = { 0 };
//char buf[8] = { 0 };
char* pBuf = buf;
int charPos = 32;
int radix = 1 << 1;
int mask = radix - 1;
do
{
pBuf[--charPos] = digits[i & mask]; // 与运算获取每次提取的数据
i = i >> 1;
} while (i != 0);
std::string str;
int strLen = 32 - charPos;
int zeroLen = 0;
while (zeroLen < charPos)
{
str.push_back(48);
zeroLen++;
}
pBuf = pBuf + charPos;
while (strLen)
{
str.push_back(*pBuf);
pBuf++;
strLen--;
}
return str;
}
二、返回char* 类型
char digits[] =
{
'0','1','2','3','4','5',
'6','7','8','9','a','b',
'c','d','e','f','g','h',
'i','j','k','l','m','n',
'o','p','q','r','s','t',
'u','v','w','x','y','z'
};
char* ToBinaryString_Test(int i)
{
char buf[32] = { 0 };
//char buf[8] = { 0 };
char* pBuf = buf;
int charPos = 32;
int radix = 1 << 1;
int mask = radix - 1;
do
{
char a = digits[i & mask];
pBuf[--charPos] = digits[i & mask]; // 与运算获取每次提取的数据
i = i >> 1;
} while (i != 0);
// 需要在堆上分配空间。如果在栈上分配空间,函数执行完毕后,栈空间被释放,char* 指针指向的地址被释放后,会返回乱码。
char* str = new char[33]{ 0 };
int strLen = 32 - charPos;
int zeroLen = 0;
for(int i = 0; i < charPos; i++)
{
str[i] = 48;
zeroLen++;
}
pBuf = pBuf + charPos;
while (strLen)
{
int a = (*pBuf);
str[zeroLen] = (*pBuf);
pBuf++;
strLen--;
zeroLen++;
}
str[32] = '\0';
return str;
}