Thread: itoa, binary, negative numbers and 2's compliment

  1. #1
    Registered User
    Join Date
    Oct 2009

    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:

    int diff, lower,higher;
    char biChra[16];
    string biStr;
    itoa (diff,biChra,2);
    ostringstream biStrout (biStr);
    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
    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. #2
    Registered User
    Join Date
    Oct 2009
    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. #3
    The larch
    Join Date
    May 2006
    In C++ there's also bitset:

    #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';
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Negative numbers in C
    By BlaX in forum C Programming
    Replies: 18
    Last Post: 06-29-2009, 06:30 PM
  2. Bitwise OR
    By tinkerbell20 in forum C++ Programming
    Replies: 4
    Last Post: 06-11-2005, 02:23 AM
  3. Question regarding 8/16-bits 2's complement numbers
    By mobius in forum C Programming
    Replies: 1
    Last Post: 09-02-2001, 11:49 PM