I want convert integer to byte. If integer bigger than byte range{0,255} then counting from the start. I mean if integer = 260 then function return 5 or if int = 1120 then return 96 and so on.
Asked
Active
Viewed 152 times
-3
-
Just cast it to byte: `byte b = (byte) yourInt;` – Evk Apr 02 '18 at 06:51
-
There is a discrepancy in the expected results for this question, so the question marked as a duplicate doesn't answer it sufficiently. The answer below addresses this discrepancy, so I have reopened this question. – Matthew Watson Apr 02 '18 at 08:02
1 Answers
1
You can use:
byte myByte = (byte)(myInt & 0xFF);
However, note that 260 will give 4 instead of five. (E.g. 255->valid, 256->0, 257->1, 258->2, 259->3, 260->4)
If you really want 260 to give 5, then you are probably looking for the remainder after dividing by 255. That can be calculated using:
byte myByte = (byte)(myInt % 255);

Peter Aylett
- 750
- 3
- 8
-
Is `byte myByte = (byte)(myInt & 0xFF);` any different from directly casting to `byte`? – InBetween Apr 02 '18 at 06:58
-
If primitive operations are enforced to be unchecked, then there is no difference. However, if an overflow check occurs, values outside the range of byte will cause an exception. – dumetrulo Apr 02 '18 at 07:01
-
Note that you could also use `byte myByte = unchecked((byte)myInt);` – Matthew Watson Apr 02 '18 at 07:59
-
Also note that `1120 % 255` is `100` whereas `1120 & 0xff` is `96`. There is a discrepancy in the OP's expected results which s/he will need to address - but this answer correctly states both possible solutions. – Matthew Watson Apr 02 '18 at 08:05