# itoa, binary, negative numbers and 2's compliment

This is a discussion on itoa, binary, negative numbers and 2's compliment within the C++ Programming forums, part of the General Programming Boards category; hi, i need to get a negative int into its 2's complement binary representation. i was screwing around with the ...

1. ## itoa, binary, negative numbers and 2's compliment

hi, i need to get a negative int into its 2's complement binary representation.

i was screwing around with the itoa() function and found that when i put the base input as 2, it would turn my negative numbers into 2's compliment, so i tried implementing this into my project as so:

Code:
```int diff, lower,higher;
char biChra[16];
string biStr;

diff=lower-higher;
itoa (diff,biChra,2);
ostringstream biStrout (biStr);
biStrout<<setw(16)<<biChra;
return biStrout.str();```

say if lower=4 and higher=13, then diff =-9, and theoretically, itoa should give me 1111 1111 1111 0111, which i then want to return as a string.

however, it throws a "Unhandled exception: ... Access violation writing location" error, and when i mouse over biChra, it shows
Code:
`biChra = 0x0013f1a8 "11111111111111111111111111110111"`
which is a bit more than 16 digits, but still equivalent to -9 in 2's comp binary.

so, what im getting at is, is this an issue with itoa()? if so, are there any other functions that can output in 2's comp binary, or will i have to write a function of my own? (i've seen sprintf thrown around a lot, but it doesn't look like it can convert to binary)

2. ugh, i just realized that the array must be long enough to accept all the bits from the function (32 in this case) plus one for the null character. so just setting biChra to 33 instead of 16 should fix it

3. In C++ there's also bitset:

Code:
```#include <iostream>
#include <bitset>
#include <string>

int main()
{
std::bitset<16> bs(static_cast<unsigned>(-9));
std::string bits(bs.to_string<char, std::char_traits<char>, std::allocator<char> >());
std::cout << bits << '\n'; //1111111111110111
//or just
std::cout << bs << '\n';
}```