Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int into a base 2 cstring/string

In visual studio on my PC I can use itoa() to convert from a base ten int to a base 2 c-string. However when I am on a Linux machine that function isn't supported. Is there another quick way of doing this kind of conversion? I know how to use a string stream and I can use the dividing and modding to convert to another base manually.

I was just hopping that there was an easier way of accessing the binary representation of an int.

like image 478
Schuyler Avatar asked Dec 27 '22 00:12

Schuyler


1 Answers

You could use std::bitset<N> with a suitable N (e.g., std::numeric_limits<int>::digits):

std::string bits = std::bitset<10>(value).to_string();

Note that ints just represent a value. They are certainly not base 10 although this is the default base used when formatting them (which can be easily change to octal or hexadecimal using std::oct and std::hex). If anything, ints are actually represented using base 2.

like image 104
Dietmar Kühl Avatar answered Jan 10 '23 13:01

Dietmar Kühl