Storing hex literals as a Java Byte

I've been challenged to implement the government-supported Advanced Encryption Standard (AES) in whatever programming language I wish. I decided to write it up in Java, since I've been using that for the past year now. It's been going pretty well so far, but ran into a rather trivial speed bump at the start.

I wanted to define a hard-coded array of Bytes as my plaintext to get encrypted and decrypted. This led me to try out the following line:

Byte[] plaintext = new Byte[]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF};

This takes advantage of a nice feature in Java where I can define numbers primitively in hex, binary, octal, or decimal: link.

However, this line was bringing up lots of compiler errors, all giving the message "incompatible types: int cannot be converted to Byte".

It took a lot of shuffling around to see how to get past this error. The most frustrating part was that I changed the hex literals to their equivalent binary and octal literals, and the errors went away. Why doesn't a hex literal work?! I finally found a suggestion to cast the hex values to a byte. Sure enough, this also got the errors to go away.

All three suggestions leave the code pretty ugly-looking, but it works:

Byte[] plaintext = new Byte[]{(byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0xAA, (byte)0xBB, (byte)0xCC, (byte)0xDD, (byte)0xEE, (byte)0xFF};

Comments

Popular Posts