2010-12-07 22 views
2

我一直在研究一个将数字转换为二进制的程序。正如你可以看到我的程序here,我已经写了这样的话,它可以扩大数字,然后传统的二进制代码,比如2行(16位)的数字大于255。然而,更大的需要长而不是int ,但似乎表现不佳,产出如this。任何人都不介意帮我改变程序使用很长时间吗?或者是否需要对代码进行根本性更改而不是进行一些小修改?在C++中使用long和数组

#include <iostream> 
#include <math.h> 
using namespace std; 
int main(int argc, char **argv) 
{ 
    int j=0; 
    int c=8; 
    long a = 1; 
    int i=1; 
    cin >> a; 
    while (a >= (pow(2,c))) { 
     c = c+8; 
     i++; 
     } 
    long block[i*8]; 
    for (long tw;tw<(i*8);tw++) 
    { 
     block[tw] = 0; 
    } 
    j=((i*8)-1); 
    long b = 0; 
    while (j != -1) 
    { 
     if (b+(pow(2,j))<=a) 
     { 
      block[j]=1; 
      b=b+(pow(2,j)); 
     } 

     j--; 
    } 
    long q=0; 
    cout << endl; 
    int y=1; 
    long z = 0; 
    for (y;y<=i;y++) { 
     for (z;z<8;z++) { 
      cout << block[z+q]; 
     } 
     cout << endl; 
     z = 0; 
     q = q + (8*y); 
     } 
    } 
+0

只是好奇,女巫是你的第一个编程语言? – ruslik 2010-12-07 21:34:58

回答

2

你让你的代码比它需要的复杂得多。这将打印出一个单一的32位整数二进制:

const unsigned int bit_count = sizeof(int) * 8 - 1; 

int a; 
std::cin >> a; 

for (unsigned int i = bit_count; i > 0; --i) 
{ 
    unsigned int t = (1 << i); 
    std::cout << (a & t ? "1" : "0"); 
} 
std::cout << (a & 1 ? "1" : "0"); 
std::cout << std::endl; 

如果要通过范围内阻止其关闭,以使其更易于阅读,你只需要放在循环范围(或移动到一个函数,需要一个范围)。

0

为什么不是这样简单的东西?您可以将中间位存储在数组或字符串中,而不是使用cout。

int convert(long n) 
{ 
    long k=1; 
    while(k<n)//find the most significant bit 
    { 
     k*=2; 
    } 
    if(k>n)//fix the overshoot 
    { 
     k/=2; 
    } 

while(k>0) 
{ 
    if(int(n/k)%2==0) 
    { 
     cout<<0;//find the (next) most 
    } 
    else 
    { 
     cout<<1;//significant binary digit 
    } 
    k/=2;//go to the next column to the right and repeat 
} 
} 
0

对于更灵活一点,这里有另一种方式来使用模板。由于扩展问题,有意删除带签名类型的模板实例。

template <typename T> 
void print_binary(const T input, const short grouping = 4) 
{ 
    unsigned int bit_count = sizeof(T) * 8; 
    T nth_bit = 1 << (bit_count - 1); 

    for(int i = 0; i < bit_count; i++, nth_bit >>= 1) 
    { 
     cout << (input & nth_bit ? "1" : "0"); 
     if(i % grouping == grouping-1) // print binary in groups 
      cout << ' '; 
    } 

    cout << endl; 
} 

template <> 
void print_binary<signed>(const signed input, const short grouping); 
template <> 
void print_binary<signed short>(const signed short input, const short grouping); 
template <> 
void print_binary<signed long>(const signed long input, const short grouping); 
template <> 
void print_binary<signed char>(const signed char input, const short grouping);