C++ reading a sequence of binary numbers

Discussion in 'Software' started by Antbert, Nov 22, 2008.

  1. Antbert

    Antbert Private E-2

    Using C++ I basically want to look at, for example, the number 011110100001 but look at every number individually, then move along to the next one (this is to make a programme that does Lempel Ziv coding).

    I can't figure out how to look at each number individiually rather than it look at the whole thing as one number.

    Also (it's been quite a while since I've used C++), what's the variable definition for binary?

    I'm not sure I explained that very well so I can elaborate if necessary.

    Thanks
     
  2. PC-XT

    PC-XT Master Sergeant

    You can use the test (2^c&n!=0) for an int, n, to see if bit number c (numbered from the right, with the rightmost bit being numbered 0) is set to 1 (true) or 0 (false)
    That is, 2 to the power of c, ANDed with n, will be 0 if bit c of n is 0, (otherwise it will be 2^c AND n).

    If using floating point, values for c may also be negative, and the function will probably need some tweaks, for instance using pow(). I am not sure how & works on floats, either.

    Alternatively, you can convert it to a string representation of binary and look at each character, but this is often just extra work, unless you don't have any calculations on the whole number, but are working directly with the bits.
     
    Last edited: Nov 22, 2008
  3. PC-XT

    PC-XT Master Sergeant

    Actually, that formula was only for unsigned ints, although I think it would work for signed floats, but you would have to check the sign bit with n<0.

    For any signed or unsigned int, the formula to return one bit's value is n>>c&1, which shifts bit # c to the one's place, then resets all the other bits. The value of the result will be the value of bit # c. This is also generally more efficient than the method I gave previously.
     
  4. Antbert

    Antbert Private E-2

    OK cool thanks. I'll give it a go and then undoubtedly return with more questions.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds