How to convert an int to a binary string represen

2019-01-22 21:23发布

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

9条回答
劫难
2楼-- · 2019-01-22 21:30

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.

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.

查看更多
叼着烟拽天下
3楼-- · 2019-01-22 21:32

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";
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-22 21:34

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

Example:

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"
查看更多
唯我独甜
5楼-- · 2019-01-22 21:35

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

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-22 21:37

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

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

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

  • 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)
查看更多
ら.Afraid
7楼-- · 2019-01-22 21:38

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

查看更多
登录 后发表回答