将小数转换为8位的二进制

时间:2018-01-15 18:52:43

标签: c++ binary decimal

// C++ program to convert a decimal
// number to binary number

#include <iostream>
using namespace std;

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

// Driver program to test above function
int main()
{
    int n = 2;
    decToBinary(n);
    return 0;
}

我想知道8位的转换是怎样的。因为如果你把2,答案将是10,但我想实现它,因此它可以成为00000010

3 个答案:

答案 0 :(得分:2)

由于这是标记为C ++,这对你有用吗?

#include <iostream>
#include <bitset>

int main(int argc, char *argv[])
{
    std::bitset<8> bits(2);

    std::cout << bits << "\n";

    return 0;
}

答案 1 :(得分:0)

如果您认为输入数字符合8位,则可以将打印代码更改为:

for (int j = 7; j >= 0; j--)
   cout << binaryNum[j];

如果您希望能够以8位的倍数打印所有数字,可以将其更改为:

int bits = 8;
if ( i > 8 )
   bits = 8*((i + 7)/8);


for (int j = bits-1; j >= 0; j--)
   cout << binaryNum[j];

此外,请确保对数组进行零初始化以避免未定义的行为。

int binaryNum[1000] = {};

A working example

// C++ program to convert a decimal
// number to binary number

#include <iostream>
using namespace std;

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000] = {};

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    int bits = 8;
    if ( i > 8 )
       bits = 8*((i + 7)/8);

    for (int j = bits-1; j >= 0; j--)
       cout << binaryNum[j];

    cout << endl;
}

// Driver program to test above function
int main()
{
    int n = 2;
    decToBinary(n);
    decToBinary(3200);
    decToBinary(3200000);
    return 0;
}

及其输出:

00000010
0000110010000000
001100001101010000000000

答案 2 :(得分:0)

您可以使用查找表:

static const char conversion_table[] =
{
  "00000000", "00000001", "00000010", "00000011",
  "00000100", "00000101", "00000110", "00000111",
//...
  "11111100", "11111101", "11111110", "11111111",
};

std::string result = conversion_table[24];
std::cout << "Decimal 24 in binary: " << result << std::endl;

查找表非常快。