0

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 ?

5
  • I think you'd better use C/C++ for this! Commented Nov 23, 2013 at 14:01
  • please give the reasosn you use byte instead of Integer for this Commented Nov 23, 2013 at 14:02
  • 1
    Remember that the byte type in Java is signed - it represents -128 to +127, not 0 to 255. Commented Nov 23, 2013 at 14:10
  • it's kind of homework where we need to implement it as byte... if I could decide this by my own, I would use C as mentioned ;) Commented Nov 23, 2013 at 14:47
  • I found a way to display the binary representation of bytes and it seems to be that a simple ++ operator does exactly what I want. Commented Nov 23, 2013 at 16:20

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

2 Comments

is there a possibility to do that using var type byte without casting?
Well, in that case, i really dont know about anything alse than use C/C++ instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.