Home > Back-end >  How to edit the values of hexadecimal integer in Java?
How to edit the values of hexadecimal integer in Java?

Time:09-28

I'm trying to edit values in a hexadecimal in Java.

For example:

int j = 0xAARRGGBB

How would I change the value of AA or RR after the integer has been created?

I couldn't find this question answered anywhere on Google.

Thank you so much for the help! -Jai

CodePudding user response:

Bitwise and (&) can be used to clear specific bits:

int j = 0xff224488;

j = j & 0xffff00ff;     // j is now 0xff220088

Bitwise or (|) can be used to set specific bits:

int j = 0xff224488;

j = j & 0xffff00ff;     // j is now 0xff220088

j = j | 0x00003300;     // j is now 0xff223388

CodePudding user response:

Here is all you need I guess to do that

public static int toARGB(int a,int r,int g,int b){
  return ((((((a << 8) | r) << 8) | g) << 8) | b);
}

public static int setB(int origin,int value){
  return set(origin,0,value);
}
public static int setG(int origin,int value){
  return set(origin,1,value);
}
public static int setR(int origin,int value){
  return set(origin,2,value);
}

public static int setA(int origin,int value){
  return set(origin,3,value);
}

public static int set(int origin,int pos,int value){
  return (origin & ~(0xFF << (pos * 8)) | value << (8 * pos));
}
  • Related