Dynamically add 0x prefix to int in Java


int i = 16777215;

void draw(int color) {


}

Lets say void draw expects the color to start with the 0x prefix like so

draw(0x16777215)

If I try this it throws a syntax error

draw(0x + i)

Invalid hex literal number

int i cannot contain the 0x part, it needs to be dynamically added

thanks


Answers:


0x1234 is just another way of writing an integer value. For instance, 0xff and 255 are exactly the same thing. draw(0x16777215) and draw(376926741) are identical calls. At the bytecode level, there's not any difference. The only difference is to how it appears to a human reading the code; sometimes it's easier to think in terms of bytes, which are easily expressed in hex.

If a number starts with 0x, it means the rest of the digits are interpreted as hex. Instead of 0x16777215, I'm guessing you wanted 16777215 (without the 0x), which is also 0xFFFFFF.

The Oracle tutorial on primitive datatypes has a bit more information (and more authority than I do :) ).

To demonstrate that it's all the same under the hood, you can look at some disassembled code. Consider this class:

public class Hexes {
  public static int alpha = 0x16777215;
  public static int beta = 376926741;
}

Running javap -c Hexes after compiling Hexes.java will show you what's happening under the hood:

Compiled from "Hexes.java"
public class Hexes {
  public static int alpha;

  public static int beta;

  public Hexes();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  static {};
    Code:
       0: ldc           #2                  // int 376926741
       2: putstatic     #3                  // Field alpha:I
       5: ldc           #2                  // int 376926741
       7: putstatic     #4                  // Field beta:I
      10: return
}

The block labeled static {} is the class' static initializer, where alpha and beta are set. Note that the two fields (alpha and beta) are both assigned the same int value. If you were to write a short program to print the values out, you'd see the same value for each:

public class HexesPrinter {
    public static void main(String[] args) {
        System.out.println(Hexes.alpha);
        System.out.println(Hexes.beta);
    }
}

Output:

376926741
376926741