1. 程式人生 > >將long整型轉為二進位制和16進位制,存於字串中

將long整型轉為二進位制和16進位制,存於字串中

1.將Long整型轉為二進位制

#include<iostream>
#include <vector>
#include <assert.h>
#include <string>
using namespace std;


char *get2String(unsigned long num)
{
	char *buff = new char[33];
	long temp;
	for (int i = 0; i < 32; i++)
	{
		temp = num&(1 << (31 - i));
		temp = temp >> (31 - i);
		buff[i] = (temp == 0 ? '0' : '1');
	}
	buff[32] = '\0';
	return buff;
}


int main(void)
{
	cout << get2String(1024) << endl;
	return(0);
}

注意:沒有考慮符號為負的情況

2.將Long整型轉為十六進位制

#include<iostream>
#include <vector>
#include <assert.h>
#include <string>
using namespace std;


char *get16String(unsigned long num)
{
	char *buff = new char[11];
	buff[0] = '0';
	buff[1] = 'x';
	buff[10] = '\0';
	char *temp = buff + 2;
	for (int i = 0; i < 8; i++)
	{
		temp[i] = (num << 4 * i) >> 28;  //28是因為每次把需要的4位元組都移到最高位了
		temp[i] = temp[i] >= 0 ? temp[i] : temp[i] + 16;  //temp[i]可能是負值(最高位為1),將其轉為0-15之間
		temp[i] = temp[i] < 10 ? temp[i] + 48 : temp[i] + 55;
	}
	return buff;
}


int main(void)
{
	cout << get16String(2147483647) << endl;
	return(0);
}