java integer color to flutter color and back

Robin Dijkhof :

I'm rebuilding my app from java to flutter. I'm using firebase to store colors as integer values. In java I can use the following to convert rgb values to integer values:

colorInt = (255 << 24) | (color.red << 16) | (color.green << 8) | color.blue;

And I can use the following to convert from an integer value to rgb:

int r = (colorInt >> 16) & 0xFF;
int g = (colorInt >> 8) & 0xFF;
int b = colorInt & 0xFF;

How can I convert a Java integercolor to a flutter color and back?

An example, lets take RGB 154, 255, 147

In flutter this would be the result is 4288348051

(255 << 24) | (154 << 16) | (255 << 8) | 147;
(4278190080) | (10092544) | (65280) | 147;

(4278190080) | (10092544) = 4288282624;
(4278190080) | (10092544) | (65280) = 4288347904;
(4278190080) | (10092544) | (65280) | 147 = 4288348051

In java this would be -6619245

(255 << 24) | (154 << 16) | (255 << 8) | 147;
(-16777216) | (10092544) | (65280) | 147;

(-16777216) | (10092544) = -6684672;
(-16777216) | (10092544) | (65280) = -6619392;
(-16777216) | (10092544) | (65280) | 147 = -6619245;
AKushWarrior :

So, as @Ovidiu mentioned, Java uses signed 32 bit integers. Expanding on the code block they posted, we can create a full example which gives us what we need:

import 'dart:math';

int chopToJavaInt (int result) {
  while (result > pow(2, 31)) {
    result = result - pow(2, 32);
  }
  return result;
}

int javaIntColor(int r, int g, int b) {
  var x = (g << 24) | (r << 16) | (g << 8) | b;
  return chopToJavaInt(x);
}

void main () {
  print(javaIntColor(154, 255, 147)); //-6619245
}

This solution is modular, maintains your original style from your Java code, and will return the correct value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=321888&siteId=1