I want to use a var of type byte to implement a counter which counts from 0 to 255 and starts again by 0. What's the best method to increment a byte just by 1, is it possible to do it without type casting? Is there a method which resets 0xff to 0x00 automatically when adding +1 ?
1 Answer
int myCounter = 255;
//increment
myCounter = (myCounter+1) % 256;
//or even faster hack
myCounter = (myCounter+1) & 0xFF;
also note that if you for any reason need to increment very often and very fast, and then occasionaly read, you can increment without moduling / masking, and modulo / mask the counter at the time you read its value
2 Comments
Karl Adler
is there a possibility to do that using var type byte without casting?
kajacx
Well, in that case, i really dont know about anything alse than use C/C++ instead
bytetype in Java is signed - it represents -128 to +127, not 0 to 255.