2

I'm following a tutorial to write an emulator for the Chip8. Opcodes are 2 bytes long and in HEX. They are stored in unsigned short data types (which is 2 bytes).

I want to get the last byte off of one of these shorts and save it on a char (1 byte).

I have tried using the & operation to filter out the first byte and then assign to a char variable.

unsigned short opcode = 0x56FA; //sample opcode
char mychar = opcode & 0x00FF;  //& operation to make 1st byte zeros
printf("%02X \n", mychar);      //should print last byte FA

I expect for it to print FA. but instead prints out FFFFFFFA.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
Leon
  • 31
  • 3

2 Answers2

3

When you write printf("%02X \n", mychar); mychar is promoted to an integer and that integer is then printed. In your case mychar is signed and is in fact negative, so the value is promoted to a negative integer and you are getting the output FFFFFFFA. If instead you use unsigned char then you will get the expected output.

Your question seems like a duplicate of this question and this answer is better than mine.

MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
1

You need to cast to a char to truncate the short into a char. Casting converts the binary value into the correct length.

short = 5; --> 0000 0000 0000 0101 When casting it becomes --> 0000 0101 Truncating the short to a char.

unsigned char opcode = (char)(opcode & 0x00ff)