生成十进制到二进制时出错

Error generating decimal to binary

我正在编写一个程序来获取数字的二进制表示形式。 我写了这段代码。

#include <iostream>

using namespace std;
int main() {
    int n, count = 0;;
    int* br = new int();
    cin >> n;
    while (n>0) {
        if (n % 2)
            br[count] = 1;
        else
            br[count] = 0;
        n /= 2;
        count++;
    }
    cout << count << endl;
    for (int i = count - 1; i >= 0; i--) {
        cout << br[i];
    }
    return 0;
}

当我运行上面的程序时我得到这个错误

Program received signal SIGTRAP, Trace/breakpoint trap.
0x00007ffe8995a2dc in ntdll!RtlpNtMakeTemporaryKey () from C:\Windows\SYSTEM32\ntdll.dll
Single stepping until exit from function ntdll!RtlpNtMakeTemporaryKey,
which has no line number information.
gdb: unknown target exception 0xc0000374 at 0x7ffe8995a31c

Program received signal ?, Unknown signal.
0x00007ffe8995a31c in ntdll!RtlpNtMakeTemporaryKey () from C:\Windows\SYSTEM32\ntdll.dll
Single stepping until exit from function ntdll!RtlpNtMakeTemporaryKey,
which has no line number information.
[Inferior 1 (process 6368) exited with code 0377]

可能是什么原因。 我是 C++ 新手。

说明

int* br = new int();

只分配一个整数。您应该至少分配与要转换的数据一样多的位(32?64?)。 我认为你最好使用静态数组,所以

int br[64] ;

您应该使用整数数组来保存各个位。现在您的代码正在创建一个动态 int :

int* br = new int();

由于 int 的大小随实现的不同而变化,因此一种可移植的方法是:

#include<climits>
.....
int* br = new int[sizeof(int)*CHAR_BIT];

CHAR_BIT 是来自 "Number of bits in a char object (byte)" 的常数。 sizeof(int) 是 int 中字符(字节)的数量。 将两者相乘,你得到一个 int 中的位数。

虽然你并不真的需要动态内存。使用堆栈内存更容易也更合适:

#include<climits>
.....
int br[sizeof(int)*CHAR_BIT];

前面的解决方案都有一个共同的问题。它们都使用一个整数来存储一个位。这意味着浪费了超过 90% 的存储 space。这个问题对于这样一个简单的例子来说是微不足道的,但在更大的项目中可能会成为现实。
std::bitset 是一个很好的改进方法:

A bitset stores bits (elements with only two possible values: 0 or 1, true or false, ...).

The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char).

#include<climits>
#include<bitset>
.....
bitset<sizeof(int)*CHAR_BIT> br;

std::bitset 设计得很巧妙,你只需要改变 br 的声明就可以了,不需要改变其余的代码。