Thread: Working with Binary Numbers in C++

  1. #16
    Join Date
    Mar 2005
    On a side note, a byte is not always 8 bits...

    static int size = sizeof(unsigned long) * 8;
    Here is code I wrote that uses the correct byte size depending on ur system...
    template <typename ChildType>
    string ConvtoBin (ChildType eData) 
       string bits;
       for (int a = sizeof(eData) * CHAR_BIT; a > 0; a--) 
          bits += ((eData >> a) & 1) + 48;
       return bits;

  2. #17
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Two things:
    1. As JoshR pointed out, not all systems will be 8 bits/byte. Another valid solution is to use numeric_limits as I have, but make sure to do so with unsigned char, rather than char.
    2. While you have used the same function I wrote, I would recommend converting to std::string from char*. The reason for this is that there is a memory leak. Notice that I assigned the pointers to named variables, and then called delete[]. This is because memory was allocated with new[], and so, must be deallocated by the user.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #18
    Registered User
    Join Date
    Nov 2004
    thanks for all the suggestions.

    JoshR I tried your method for doing the circular right shift but it didn't work as expected because of the data type being char therefore, the numbers weren't displayed.

    As for the size, I want it to be 32 bit binary number for all values.

  4. #19
    Join Date
    Mar 2005
    Char is just a one byte data type, you can display the number with (int) num.

    Or you can use an int and do the same thing just you add a bigger number but it works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reducing rational numbers - code not working properly
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 04-17-2009, 07:42 AM
  2. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  3. Working with Strings and Numbers
    By jamez05 in forum C++ Programming
    Replies: 8
    Last Post: 10-19-2005, 12:39 PM
  4. binary
    By webturtle0 in forum A Brief History of
    Replies: 52
    Last Post: 12-05-2002, 02:46 AM
  5. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM