Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bit shifting question

Status
Not open for further replies.

sergeiY

Programmer
Feb 13, 2003
132
AU
Hi

I am looking at some somple code that creates histogram for a color ... I do understand all but one bit here and I suspect it's a bit shifting operation. Can anybody please explain to me what is it ?

Here is the code:

Code:
//calculate histogram for blue
//count instances each color
histArray = new double[256];
for(int i = 0; i <width; i++)
   for(int y = 0; y <height; j++)
      histArray[imageInt[i][j] & 0xFF] ++

I do understand that it counts number of color in image but why does it need to to this & 0xFF ???

Thank you
 
a bit more codes would help. As of right now, I think the bitwise & makes sure that the index assigned to histArray is less than 256 exclusively.

In other words, the index for histArray, because of the bitwise operator &, will make sure the array index is:-

histArray[0] ..... histArray[255]

This will prevent a runtime error IndexOutOfBound from being generated at runtime.

0xFF using a simple calc will be 255(in decimal) or 11111111 in binary.


~za~
You can't bring back a dead thread!
 
Oooook ... now it makes sence so I could've done % 256 and it would've been same result right ?
 
That is a pretty savvy way to avoid using try and catch block :)

you could play with the modulus operator(%) and see the result. Take a couple of big numbers and see if they still fall within the range. Else, to improvise the code, add the try and catch block so if exceptions happen at runtime, it will be caught. Still the & operator does a superb job. Unfortunately, in real life few people actually use bitwise operators. That's a shame :(

~za~
You can't bring back a dead thread!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top