[SOLVED] Problem fetching a Chip-8 opcode

I’m really not sure if this is the right forum to ask this question, as this is not a game but an emu/interpreter but I’m freaking out over here.

Long story short:

I have to fetch the first two bytes from a byte array, which are A2 and CC (in hexadecimal of course).

For that task I do the following…

int opcode = memory[pc] << 8 | memory[pc+1]

But instead of give me “A2CC” together it gives me “FFCC”

Please JGO I’m about to hang myself.

Thank you.

wouldnt something like: “memory[pc]*256 + memory[pc+1]” give the desired result?

byte one = (byte) 0xA2;
byte two = (byte) 0xCC;
		
System.out.println(Integer.toHexString(one) + " " + Integer.toHexString(two));
		
int op = one << 8 | two;
		
System.out.println(Integer.toHexString(op));

Prints [quote]ffffffa2 ffffffcc
ffffffcc
[/quote]

byte one = (byte) 0xA2;
byte two = (byte) 0xCC;
		
System.out.println(Integer.toHexString(one & 0xFF) + " " + Integer.toHexString(two & 0xFF));
		
int op = one << 8 & 0xFF00 | two & 0xFF;
		
System.out.println(Integer.toHexString(op));

Prints: [quote]a2 cc
a2cc
[/quote]
EDIT: formatting

@liquidnitrogen Thank you, that actually worked but for some reason the first opcode came wrong and the next in line came perfect.

Sadly if the first opcode is wrong the whole thing wont work.

@burntpizza thank you that solve my problem.

Now i have another question: Why in every Chip-8 tutorial appears as

memory[pc] << 8 | memory[pc+1]

Is there something different in how java manages bits?

It has to do with what happens when you cast back and forth between byte and int (and that all java primitives other than char are signed):

for (int i = 0; i < 256; i++) {
    byte b = (byte) i; // explicit down-cast
    System.out.println(Integer.toHexString(i) + ": " + Integer.toHexString(b)); // implicit up-cast
}

Prints

[quote]…
7d: 7d
7e: 7e
7f: 7f
80: ffffff80
81: ffffff81
82: ffffff82

[/quote]
EDIT:
Using the unsigned char for the original problem:

char op = (char) (one << 8 | two & 0xFF);

Prints the desired output. Using [icode]short[/icode] doesn’t.