/*
编程实现把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列。
//*/
// 使用移位操作,二进制可以左移,16进制采用右移
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
template <class T>
void swap_t(T &lp, T &rp){
T tmp = lp;
lp = rp;
rp = tmp;
}
template <class T>
void reverse(T data[], int begin, int end)
{
while(begin < end){
swap_t(data[begin], data[end]);
++begin;
--end;
}
}
/*
int main(int argc, char** argv)
{
if(argc < 2)
return -1;
char Href[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','\0'};
char Binref[] = "0000000100100011010001010110011110001001101010111100110111101111";
int val = atoi(argv[1]);
char hex[50];
char bin[50];
int i = 0;
while(val > 16){
hex[i] = Href[val%16];
i += 1;
val /= 16;
}
hex[i] = Href[val];
hex[i+1] = '\0';
reverse(hex, 0, i);
cout << "十六进制输出: \t" <<"0X" << hex << endl;
int k = 0;
for(int j = 0; j <= i; ++j){
if(hex[j] <= '9'){
for(k = 4*j; k < 4*(j+1); ++k){
bin[k] = Binref[(hex[j] - '0') * 4 + k - j*4]; // 按十六进制编码索引二进制编码
}
}else{
for(k = 4*j; k < 4*(j+1); ++k){
bin[k] = Binref[(hex[j] - 'A' + 10) * 4 + k - j*4];
}
}
}
bin[k] = '\0';
cout << "二进制输出: \t" << bin << endl;
return 0;
}
//*/
int main(int argc, char** argv)
{
if(argc < 2)
return -1;
char Href[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','\0'};
//char Binref[] = "0000000100100011010001010110011110001001101010111100110111101111";
int val = atoi(argv[1]);
int bref = 1;
bool barr[50];
int idx = 0;
while(val > 0){
if(val & 1){
barr[idx] = 1;
++idx;
val = val >> 1;
}else{
barr[idx] = 0;
++idx;
val = val >> 1;
}
}
int zeros = 0;
if(idx%4 != 0){
zeros = 4 - idx%4;
for(int zr = 0; zr < zeros; ++zr){
barr[idx+zr] = 0;
}
}
idx = idx + zeros;
reverse(barr, 0, idx -1);
for(int i = 0; i < idx; ++i)
cout << barr[i];
cout << endl;
int val16 = 0;
if(idx%8){
cout <<"0x0";
}else{
cout <<"0x";
}
for(int i = 0; i < idx; i = i+4){
val16 = barr[i] * 8 + barr[i+1] * 4 + barr[i+2] * 2 + barr[i+3];
cout << Href[val16];
}
cout << endl;
return 0;
}
编程实现把十进制数(long型)分别以二进制和十六进制形式输出
最新推荐文章于 2021-05-19 10:46:45 发布