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
Solution without reverse, no additional copy, and with 0-padding:
What exactly does that mean? There is no type "binary number". Well, an
int
is 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.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
.Anyway, to generate a base
b
representation of an integral numberx
, simply follow this algorithm:initialize
s
with the empty stringm = x % b
x = x / b
Convert
m
into a digit,d
.Append
d
ons
.If
x
is not zero, goto step 2.Reverse
s
Step 4 is easy if
b <= 10
and your computer uses a character encoding where the digits 0-9 are contiguous, because then it's simplyd = '0' + m
. Otherwise, you need a lookup table.Steps 5 and 7 can be simplified to append
d
on the left ofs
if you know ahead of time how much space you will need and start from the right end in the string.In the case of
b == 2
(e.g. binary representation), step 2 can be simplified tom = x & 1
, and step 3 can be simplified tox = x >> 1
.Solution with
reverse
:Solution without
reverse
: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'.