0

I have two byte variables byte1, byte2. I know that the difference byte1 - byte2 will involve an implicit casting to int. But if I am interested in the absolute value of the difference, and want to get abs(byte1-byte2) again in byte format, is there a way to avoid casting back to byte, i.e. avoid

byte diff = (byte) abs(byte1-byte2);

Background is efficiency in performing a large number of such differences.

Settembrini
  • 1,366
  • 3
  • 20
  • 32
  • 1
    No it's not possible without cast. see [http://stackoverflow.com/questions/21895078/why-is-the-sum-of-bytes-integer](http://stackoverflow.com/questions/21895078/why-is-the-sum-of-bytes-integer) – Johnny Willer Mar 11 '16 at 17:44
  • 1
    On modern processors, arithmetic calculations are performed on whole 32- or 64-bit words, so you won't gain any performance improvement avoiding casting even if it were possible – Alex Salauyou Mar 11 '16 at 17:50
  • what comes into mind, is to join 4 byte pairs into 2 integers or 8 pairs into 2 longs and perform arithmetic on such composite words; but I'm not sure that composition and extraction will be faster than processing each byte pair separately – Alex Salauyou Mar 11 '16 at 17:52
  • @JohnnyWiller very likely OP needs absolute difference between bytes treated as unsigned, e. g. to produce difference map between 2 images etc. – Alex Salauyou Mar 11 '16 at 18:01
  • @SashaSalauyou yes, I understood. I told him to read that question because explain numeric promotions, that is happening is his situation – Johnny Willer Mar 11 '16 at 18:03
  • Thanks, that is what I suspected. (just thought, there may be some byte shift trick...) – Settembrini Mar 11 '16 at 21:52

0 Answers0