0
public static int getARGB(final int red, final int green, final int blue, final int alpha) {
        int argb = (alpha<<24)|(red<<16)|(green<<8)|blue;
        return argb;
    }

So I have to convert the different colour ints to an argb value. Is the way I have done correct?

  • You forgot to apply (the `0xFF000000` mask optionally to the shift result of `alpha`: left-most bits will be discarded anyway, and the right-most bits will be zeroes) `0xFF0000` to the shift result of `red`, `0xFF00` to the shift result of green, and `0xFF` to `blue`. If I still remember how bit math works. :D – terrorrussia-keeps-killing Dec 21 '21 at 07:59
  • 1
    You need to check whether these values are in [0, 255) or not. If they are, then your implementation is correct. – zhh Dec 21 '21 at 08:03

1 Answers1

3

You should also add a mask to each input to make sure they are not greater than 0xFF:

int argb = (0xFF & alpha) << 24 | (0xFF & red) << 16 | (0xFF & green) << 8 | (0xFF & blue)
Ahmad
  • 73
  • 7
  • I guess `(0xFF & alpha << 24)` can be simplified to `alpha << 24`? – terrorrussia-keeps-killing Dec 21 '21 at 08:15
  • @fluffy ``<<`` has higher priority in java than ``&``, so we need to add parentheses ``(0xFF & alpha) << 24`` and so on. Since ``<<`` already has higher priority than ``|``, we do not need parentheses ;) – Ahmad Dec 21 '21 at 08:19
  • 1
    I mean another aspect, not the precedence: `int` is always a 32-bit so that shifting it by 24 bits to the left would discard the left-most bits and fill the right most 24 by zeroes... Okay, it's signed so the right-most 24 bits can be either 0 or 1 depending on the sign, so yeah, it must be masked first then shifted. Thanks for refreshing that aspect to me! – terrorrussia-keeps-killing Dec 21 '21 at 08:29
  • @fluffy you are correct, the first part(``(0xFF & alpha) << 24``) does not need the mask since the shift operator will dump the 24 leftmost bits anyway. But the code looks more readable with the mask, so I would prefer to have it :) – Ahmad Dec 21 '21 at 08:42
  • @user16320675 It depends on the application I would say, throwing an exception might not always be the best solution especially for the deployed version of an application. But we could definitely add some code to throw a warning to console when the range is violated or throw an exception when we are in debug mode – Ahmad Dec 21 '21 at 08:52