FAQ
Cover
This is the archive Discourse for the Processing (ALPHA) software.
Please visit the new Processing forum for current information.

   Processing 1.0 _ALPHA_
   Programming Questions & Help
   Programs
(Moderators: fry, REAS)
   bitwise shame!
« Previous topic | Next topic »

Pages: 1 
   Author  Topic: bitwise shame!  (Read 2217 times)
lunetta

7200475272004752 WWW Email
bitwise shame!
« on: Mar 29th, 2005, 5:08pm »

yes, my bitwise skills are a shame!
I'm wondering here what is the bitwise way to convert black to white and white to black; a operation that when performed, if the input was 0x000000 the output would be 0xffffff and vice versa.
I'm using a pair of if's in my code, but I just want to know if there was a single mathematical operation that would perform that. Just like multiplying by -1; if you have 1, it becomes -1, and if you have -1, it becomes 1.
any light?
 
toxi

WWW
Re: bitwise shame!
« Reply #1 on: Mar 29th, 2005, 7:28pm »

yes there is. it's called XOR (exclusive OR) and works like this:
 
0 XOR 0 = 1
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
 
Code:
// invert colours
int a=0;
int b=a^0xffffff;

 
this will invert the lower 24bits of an integer (RGB data) and keep the alpha information (stored in the other 8 bits) intact...
 
 

http://toxi.co.uk/
lunetta

7200475272004752 WWW Email
Re: bitwise shame!
« Reply #2 on: Mar 29th, 2005, 9:11pm »

great! really thanks!
 
Fish-face

308232952308232952thedemonsheep WWW Email
Re: bitwise shame!
« Reply #3 on: Mar 30th, 2005, 11:24am »

*cough*
 
0 XOR 0 = 0
 
Hence any number XOR itself = 0.
The table toxi posted is for the OR operator. Additionally, I though ^ was the exponentiation operator, i.e. raising to the power? If you want to bitwise OR something, it's b || a. Cannae remember how to XOR something... probably just a XOR b...
 

--

The C@ S@ on the M@
=Fish-Face=
~#Chris#~
toxi

WWW
Re: bitwise shame!
« Reply #4 on: Mar 30th, 2005, 12:46pm »

oops... fishface is correct 0^0 remains at zero, but the rest of the table is indeed correct (as is the operator itself). there's no implicit exponent operator in java, for that you'd have to use Math.pow(a,b)...
 
just to sum up once more, the expression "a XOR b" returns "true" if a!=b and "false" if a=b... the implication of this is that you can get the original value of "a" back when applying XOR with the same "b" twice.
 
Code:
int a=42;
int b=255;
a^=b;
println(a); // a is now 213
a^=b;
println(a); // a is now 42 again

 

http://toxi.co.uk/
Pages: 1 

« Previous topic | Next topic »