# Working with binary

This topic is 4339 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to work with binarys, i know the bitwise operators, but how do i check the first or last bit of a variable. I know about itoa and atoi, but do i need to convert to strings all the time? Anyone knows a tutorial about this? Thanks in advance, cya.

##### Share on other sites
and what is it exactly that you wish to accomplish.

##### Share on other sites
To work with binary, like i will make an integer and use every bit as an flag, or antoher example.. in the game othello, i will use a 64 bit variable to store the positions of white pieces and another to store the positions of black pieces, so if i want to compare two boards, i will add the two 64 bit words of each board and subtract them later, if i have a 0 then they are equal boards, something like that.

##### Share on other sites
What you want are bitwise operators, and C Programming has an intro to them.

##### Share on other sites
thanks, i will take a look at that

##### Share on other sites
int i = 7;bool bit_01 = !!(i & 0x01);bool bit_02 = !!(i & 0x02);bool bit_03 = !!(i & 0x04);bool bit_04 = !!(i & 0x08);bool bit_05 = !!(i & 0x10);bool bit_06 = !!(i & 0x20);bool bit_07 = !!(i & 0x40);bool bit_08 = !!(i & 0x80);// pattern continues...bool bit_24 = !!(i & 0x01000000);bool bit_25 = !!(i & 0x02000000);bool bit_26 = !!(i & 0x04000000);bool bit_27 = !!(i & 0x08000000);bool bit_28 = !!(i & 0x10000000);bool bit_29 = !!(i & 0x20000000);bool bit_30 = !!(i & 0x40000000);bool bit_31 = !!(i & 0x80000000);

bit_01, bit_02, bit_03 would be true, the rest false.
7d = 0x00000007 = 00000000 00000000 00000000 00000111b

You can also shift a 1 into place
(1<<8) = 0x80
(1<<31) = 0x80000000

##### Share on other sites
Is the !! necessary? If you were using C style BOOLs it would be, but I think C++ bools can only be 0 or 1.

##### Share on other sites
Quote:
 Original post by RAZORUNREALIs the !! necessary? If you were using C style BOOLs it would be, but I think C++ bools can only be 0 or 1.

(i & 0x20) == 0x20
That'll give you a warning about truncation from an int to a bool. And the bool is likely to end up as 0 all the time, since the lowest bit of 0x20 isn't set (and in theory that's the only bit that matters to a bool). Using the !! converts it to a bool.
Equally, you could do:
bool bit_06 = (i & 0x20)?true:false;
But the double !! looks nicer and is perhaps more efficient.

##### Share on other sites
To extract a random bit use this:
#include <cassert>#include <limits>template<typename T>bool get_bit(T in,unsigned int bit){    // Note: 0 is the first bit    assert( std::numeric_limits<T>::digits > bit);    return !!(in & 1<< bit );}

##### Share on other sites
Thanks Evil Steve. Seems a bit inconsistant that it branches on anything >0 but casting to a bool just depends on the least significant bit. Oh well.

##### Share on other sites
Quote:
 Original post by RAZORUNREALbut casting to a bool just depends on the least significant bit.

No, everything but zero, null pointer and null member pointer will be converted to true.
Quote:
 From the C++ Standard 2003, 4.12 Boolean conversionsAn rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

##### Share on other sites
Quote:
Original post by CTar
Quote:
 Original post by RAZORUNREALbut casting to a bool just depends on the least significant bit.

No, everything but zero, null pointer and null member pointer will be converted to true.
Quote:
 From the C++ Standard 2003, 4.12 Boolean conversionsAn rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

!!

You mean if an enumeration starts at zero, the first value is converted to true anyway? x.x

##### Share on other sites
Quote:
Original post by Zahlman
Quote:
Original post by CTar
Quote:
 Original post by RAZORUNREALbut casting to a bool just depends on the least significant bit.

No, everything but zero, null pointer and null member pointer will be converted to true.
Quote:
 From the C++ Standard 2003, 4.12 Boolean conversionsAn rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

!!

You mean if an enumeration starts at zero, the first value is converted to true anyway? x.x

No, the first value (assuming the enumerations starts from 0) is a zero value and therefore will be converted to false.

##### Share on other sites
Quote:
 Original post by Shannon Barber *** Source Snippet Removed ***bit_01, bit_02, bit_03 would be true, the rest false.7d = 0x00000007 = 00000000 00000000 00000000 00000111bYou can also shift a 1 into place(1<<8) = 0x80(1<<31) = 0x80000000

I still the don't get the !!.
(i & 0x20) == !!(i & 0x20) doesn't it?
!! == not not == true
??

##### Share on other sites
Quote:
 Original post by Evil SteveAnd the bool is likely to end up as 0 all the time, since the lowest bit of 0x20 isn't set (and in theory that's the only bit that matters to a bool).

Quote:
 Original post by CTarNo, everything but zero, null pointer and null member pointer will be converted to true.

I... think I'm gonna believe CTar. In which case I think this:
bool bit_06 = (bool)(i & 0x20);
Is much less likely to make a maintainer murderous than
bool bit_06 = !!(i & 0x20);

Quote:
 Original post by Alpha_ProgDesI still the don't get the !!.(i & 0x20) == !!(i & 0x20) doesn't it?!! == not not == true??

The problem is that (i & 0x20) won't give you 1. It'll give you... um... 32? What the !! does is make sure it's 0 or 1. And confuses most people. The first not will turn 32 into 0 or 0 into 1 you see. So if you not it again, either the 32 has become 1, or the 0 is back to 0, and you have what you want.

##### Share on other sites
Pop quiz, what does this program print?

#include <iostream>int main(){    int n_a = 1, n_b = 256;    bool a, b;    a = n_a;    b = n_b;    if(a == b)        std::cout << "cheese!" << std::endl;    else        std::cout << "peppers!" << std::endl;}

##### Share on other sites
peppers!

(because bool is only 8-bits, 256 = 0x100 which, when cast down to 8-bits = 0).

I personally just use the values for a check, like this:
#define BIT_SET(xVar, xBit) ((xVar) & (1 << (xBit)))if (BIT_SET(SomeVariable, BitPosition)){}else{}

##### Share on other sites
I figured it would be cheese, because both 1 and 256 are non zero then it would assign a true value to both a and b. So I tried it out (gcc version 3.3 on linux) and got cheese. Of course, I'm not going to assume this will be true on all compilers without reading what the standard says about it.

##### Share on other sites
Quote:
 Original post by BeerNuttspeppers!(because bool is only 8-bits, 256 = 0x100 which, when cast down to 8-bits = 0).

No. Have you checked that on a compiler? If you have, which one? Bool might be 8 bits on your platform, but it wont ever look like a number it can only hold true and false, and in undefined cases it can look like it's something else.

#include <iostream>int main(){    // Integers are able to hold the values, nothing strange happens here    int n_a = 1, n_b = 256;    // Two bools are declared their value is undefined    // it could even be something else than true or false (see 3.9.1 in the standard).    bool a, b;    // The compiler checks:    // - Is n_a a zero value? No    // - Is n_a a null pointer value? No    // - Is n_a a null member pointer value? No    // Well then it's set to true.    a = n_a;    // Again the compiler checks:    // - Is n_b a zero value? No    // - Is n_b a null pointer value? No    // - Is n_b a null member pointer value? No    // Well then it's set to true.    b = n_b;    // Both is true, so cheese    if(a == b)        std::cout << "cheese!" << std::endl;    else        std::cout << "peppers!" << std::endl;}

##### Share on other sites
Well, in our work environment (an embedded MIPS platform using codewarrior for the compiler), we have issues with people using bool and doing something like this:

bool bVar;bVar = (SomeVar & (1 << 20));if (bVar)...

Where bool is an 8-bit value but SomeVar is 32-bits and the result should be true, but isn't. So, I dunno.

EDIT:

After further review, I'm confusing the bool with a locally defined bool. I checked the disassembly of the follwoing and got the further assembly (where na and nb are passed in integers, and register-wise, s0 = nb, and s1 = na):

; 282: b = (na & (1 << nb));
; 283:
;
0x00000038 0x24030001 li v1,1
0x0000003C 0x02031804 sllv v1,v1,s0
0x00000040 0x02231824 and v1,s1,v1
0x00000044 0x0003182B sltu v1,$0,v1 ; ; 284: if (b) ; 0x00000048 0x10600005 beq v1,$0,*+24 ; 0x00000060
0x0000004C 0x00000000 nop

[Edited by - BeerNutts on April 7, 2006 4:57:33 PM]

##### Share on other sites
Embedded platforms typically have terrible compilers, even when said compilers cost insanely large amounts of money.

##### Share on other sites
ALl you need to do to convert an intergral type to a bool is to compare it with zero. i.e.
if ((x & 0x20) != 0)
It's the way to do it in strongly typed languages such as Pascal. It makes sense to do the same in C.

##### Share on other sites
!! guarantees the result is either 0 or 1 in both C and C++. It is cast over from C due to the very problem BeetNutts mentioned. There is no native bool type in C89 (one was added in C99); in C++ it avoids warnings. Sometimes you still get a warning about possible truncation even when you cast it to a bool. If you use a C++ cast, it should look like:
bool b = bool(expr & mask);

The bool snippet program above would print "peppers" with a C compiler assuming it had a typedef for bool, but in C++ bool is converted to 0 or 1 so it prints "cheese". There are other subtle type issues that relate to overloading that necessitated the addition of the bool type in C++ (e.g. the result of comparisons such as operator==() needed a unique return type, int did not work 100% correctly).

For the most part embedded compilers are caught up, and MISRA C++ is in progress. In a few more years we may finally start to see a transition from C to C++ in the embedded automotive sector.