如何在 C++ 中将 int 转换为二进制字符串表示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2890502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:24:19  来源:igfitidea点击:

How to convert an int to a binary string representation in C++

c++stringbinaryg++

提问by neuromancer

I have an int that I want to store as a binary string representation. How can this be done?

我有一个 int 想存储为二进制字符串表示形式。如何才能做到这一点?

回答by Martin York

Try this:

尝试这个:

#include <bitset>
#include <iostream>
int main()
{
    std::bitset<32>      x(23456);
    std::cout << x << "\n";


    // If you don't want a variable just create a temporary.
    std::cout << std::bitset<32>(23456) << "\n";
}

回答by fredoverflow

I have an int that I want to first convert to a binary number.

我有一个 int 想先转换为二进制数。

What exactly does that mean? There is no type "binary number". Well, an intis already represented in binary form internally unless you're using a very strange computer, but that's an implementation detail -- conceptually, it is just an integral number.

这到底是什么意思呢?没有“二进制数”类型。好吧,int除非您使用的是非常奇怪的计算机,否则an在内部已经以二进制形式表示,但这是一个实现细节——从概念上讲,它只是一个整数。

Each time you print a number to the screen, it must be converted to a string of characters. It just so happens that most I/O systems chose a decimal representation for this process so that humans have an easier time. But there is nothing inherently decimal about int.

每次在屏幕上打印数字时,都必须将其转换为字符串。碰巧的是,大多数 I/O 系统为这个过程选择了十进制表示,以便人类更轻松。但是没有什么本质上是十进制的int

Anyway, to generate a base brepresentation of an integral number x, simply follow this algorithm:

无论如何,要生成b整数的基本表示x,只需遵循以下算法:

  1. initialize swith the empty string

  2. m = x % b

  3. x = x / b

  4. Convert minto a digit, d.

  5. Append don s.

  6. If xis not zero, goto step 2.

  7. Reverse s

  1. s用空字符串初始化

  2. m = x % b

  3. x = x / b

  4. 转换m成数字,d

  5. 附加ds.

  6. 如果x不为零,则转到步骤 2。

  7. 逆转 s

Step 4 is easy if b <= 10and your computer uses a character encoding where the digits 0-9 are contiguous, because then it's simply d = '0' + m. Otherwise, you need a lookup table.

如果b <= 10您的计算机使用数字 0-9 连续的字符编码,则第 4 步很容易,因为它只是d = '0' + m. 否则,您需要一个查找表。

Steps 5 and 7 can be simplified to append don the left of sif you know ahead of time how much space you will need and start from the right end in the string.

如果您提前知道需要多少空间并从字符串的右端开始,则可以将步骤 5 和 7 简化为附加d到 的左侧s

In the case of b == 2(e.g. binary representation), step 2 can be simplified to m = x & 1, and step 3 can be simplified to x = x >> 1.

b == 2(例如二进制表示)的情况下,步骤2可以简化为m = x & 1,步骤3可以简化为x = x >> 1

Solution with reverse:

解决方案reverse

#include <string>
#include <algorithm>

std::string binary(unsigned x)
{
    std::string s;
    do
    {
        s.push_back('0' + (x & 1));
    } while (x >>= 1);
    std::reverse(s.begin(), s.end());
    return s;
}

Solution without reverse:

没有的解决方案reverse

#include <string>

std::string binary(unsigned x)
{
    // Warning: this breaks for numbers with more than 64 bits
    char buffer[64];
    char* p = buffer + 64;
    do
    {
        *--p = '0' + (x & 1);
    } while (x >>= 1);
    return std::string(p, buffer + 64);
}

回答by DVK

http://snippets.dzone.com/posts/show/4716or http://www.phanderson.com/printer/bin_disp.htmlare two good examples.

http://snippets.dzone.com/posts/show/4716http://www.phanderson.com/printer/bin_disp.html是两个很好的例子。

The basic principle of a simple approach:

简单方法的基本原理:

  • Loop until the # is 0
  • &(bitwise and) the # with 1. Print the result (1 or 0) to the end of string buffer.
  • Shift the # by 1 bit using >>=.
  • Repeat loop
  • Print reversed string buffer
  • 循环直到#为0
  • &(按位和)# 加 1。将结果(1 或 0)打印到字符串缓冲区的末尾。
  • 使用 将# 移动 1 位>>=
  • 重复循环
  • 打印反转字符串缓冲区

To avoid reversing the string or needing to limit yourself to #s fitting the buffer string length, you can:

为避免反转字符串或需要将自己限制为适合缓冲区字符串长度的 #s,您可以:

  • Compute ceiling(log2(N)) - say L
  • Compute mask = 2^L
  • Loop until mask == 0:
    • &(bitwise and) the mask with the #. Print the result (1 or 0).
    • number &= (mask-1)
    • mask >>= 1 (divide by 2)
  • 计算天花板(log2(N)) - 说 L
  • 计算掩码 = 2^L
  • 循环直到掩码 == 0:
    • &(按位和)带有# 的掩码。打印结果(1 或 0)。
    • 数字 &= (mask-1)
    • 掩码 >>= 1(除以 2)

回答by Brian R. Bondy

I assume this is related to your other question on extensible hashing.

我认为这与您关于可扩展散列的其他问题有关。

First define some mnemonics for your bits:

首先为您的位定义一些助记符:

const int FIRST_BIT = 0x1;
const int SECOND_BIT = 0x2;
const int THIRD_BIT = 0x4;

Then you have your number you want to convert to a bit string:

然后你有你想要转换为位字符串的数字:

int x = someValue;

You can check if a bit is set by using the logical &operator.

您可以使用逻辑&运算符检查是否设置了位。

if(x & FIRST_BIT)
{
    // The first bit is set.
}

And you can keep an std::string and you add 1 to that string if a bit is set, and you add 0 if the bit is not set. Depending on what order you want the string in you can start with the last bit and move to the first or just first to last.

并且您可以保留一个 std::string,如果设置了位,则向该字符串添加 1,如果未设置该位,则添加 0。根据您想要字符串的顺序,您可以从最后一位开始并移动到第一个或从第一个到最后一个。

You can refactor this into a loop and using it for arbitrarily sized numbers by calculating the mnemonic bits above using current_bit_value<<=1 after each iteration.

您可以将其重构为一个循环,并通过在每次迭代后使用 current_bit_value<<=1 计算上述助记符位来将其用于任意大小的数字。

回答by ladookie

AND the number with 100000..., then 010000..., 0010000..., etc. Each time, if the result is 0, put a '0' in a char array, otherwise put a '1'.

AND 数字与 100000...,然后是 010000...,0010000...,等等。每次,如果结果为 0,则在 char 数组中放入一个 '0',否则放入一个 '1'。

int numberOfBits = sizeof(int) * 8;
char binary[numberOfBits + 1];
int decimal = 29;

for(int i = 0; i < numberOfBits; ++i) {
    if ((decimal & (0x80000000 >> i)) == 0) {
        binary[i] = '0';
    } else {
        binary[i] = '1';
    }
}
binary[numberOfBits] = '
std::cout << ConvertInteger<Uint32>::ToBinaryString(21);
// Displays  "10101"

auto x = ConvertInteger<Int8>::ToBinaryString(21, true);
std::cout << x << "\n"; // displays "00010101"

auto x = ConvertInteger<Uint8>::ToBinaryString(21, true, "0b");
std::cout << x << "\n"; // displays "0b00010101"
'; string binaryString(binary);

回答by ladookie

There's a small header only library you can use for this here.

有一个小的头文件库,你可以在这里使用。

Example:

例子:

#include <iostream>
#include <string>

template <short WIDTH>
std::string binary( unsigned x )
{
    std::string buffer( WIDTH, '0' );
    char *p = &buffer[ WIDTH ];

    do {
        --p;
        if (x & 1) *p = '1';
    }
    while (x >>= 1);

    return buffer;
}

int main()
{
    std::cout << "'" << binary<32>(0xf0f0f0f0) << "'" << std::endl;
    return 0;
}

回答by risingballs

Solution without reverse, no additional copy, and with 0-padding:

解决方案没有反向,没有额外的副本,并且有 0-padding:

template<typename T>
std::string bstring(T n){
    std::string s;
    for(int m = sizeof(n) * 8;m--;){
            s.push_back('0'+((n >> m) & 1));
    }
    return s;
}

回答by antonyjr

This is my best implementation of converting integers(any type) to a std::string. You can remove the template if you are only going to use it for a single integer type. To the best of my knowledge , I think there is a good balance between safety of C++ and cryptic nature of C. Make sure to include the needed headers.

这是我将整数(任何类型)转换为 std::string 的最佳实现。如果您只想将模板用于单个整数类型,则可以删除该模板。据我所知,我认为在 C++ 的安全性和 C 的神秘性之间有一个很好的平衡。确保包含所需的头文件。

std::cout << bstring<size_t>(371) << '\n';

Use it like so,

像这样使用它,

0000000000000000000000000000000000000000000000000000000101110011

This is the output in my computer(it differs on every computer),

这是我电脑的输出(每台电脑都不同),

std::cout << bstring<signed int>(-1) << '\n';

Note that the entire binary string is copied and thus the padded zeros which helps to represent the bit size. So the length of the string is the size of size_tin bits.

请注意,整个二进制字符串被复制,因此填充零有助于表示位大小。所以字符串的长度是size_t的大小(以位为单位)。

Lets try a signed integer(negative number),

让我们尝试一个有符号整数(负数),

11111111111111111111111111111111

This is the output in my computer(as stated , it differs on every computer),

这是我电脑的输出(如前所述,每台电脑都不同),

std::string bstring(int n){
    std::string s;
    for(int m = sizeof(n) * 8;m--;){
            s.push_back('0'+((n >> m) & 1));
    }
    return s;
}

Note that now the string is smaller , this proves that signed intconsumes less space than size_t. As you can see my computer uses the 2's complement methodto represent signed integers(negative numbers). You can now see why unsigned short(-1) > signed int(1)

请注意,现在字符串更小,这证明了signed intsize_t消耗的空间更少。如您所见,我的计算机使用2 的补码方法来表示有符号整数(负数)。你现在可以明白为什么unsigned short(-1) > signed int(1)

Here is a version made just for signed integersto make this function without templates , i.e use this if you only intend to convert signed integersto string.

这是一个专为有符号整数制作的版本,可以在没有模板的情况下制作此函数,即如果您只想将有符号整数转换为字符串,请使用它。

##代码##

回答by Martin Beckett

There isn't a direct function, you can just walk along the bits of the int (hint see >> ) and insert a '1' or '0' in the string.
Sounds like a standard interview / homework type question

没有直接的函数,你可以沿着 int 的位走(提示参见 >> )并在字符串中插入一个“1”或“0”。
听起来像一个标准的面试/家庭作业类型的问题

回答by c4learn.com

Use sprintffunction to store the formatted output in the string variable, instead of printffor directly printing. Note, however, that these functions only work with C strings, and not C++ strings.

使用sprintf函数将格式化输出存储在字符串变量中,而不是printf直接打印。但是请注意,这些函数仅适用于 C 字符串,而不适用于 C++ 字符串。