I have an int that I want to store as a binary string representation. How can this be done?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
I assume this is related to your other question on extensible hashing.
First define some mnemonics for your bits:
Then you have your number you want to convert to a bit string:
You can check if a bit is set by using the logical
&
operator.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.
Try this:
There's a small header only library you can use for this here.
Example:
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
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:
&
(bitwise and) the # with 1. Print the result (1 or 0) to the end of string buffer.>>=
.To avoid reversing the string or needing to limit yourself to #s fitting the buffer string length, you can:
&
(bitwise and) the mask with the #. Print the result (1 or 0).Use
sprintf
function to store the formatted output in the string variable, instead ofprintf
for directly printing. Note, however, that these functions only work with C strings, and not C++ strings.