hex - Converting decimal to hexadecimal byte in Java Card -


i convert decimal (integer or short types) in java hexadecimal byte in java card environment (only supports byte , short types , possibly int types).

example:

int num = 254 

print out result:

0xfd 

my current method of using switches , if-else handle 256 scenarios totally inelegant , more elegant switches or if-else.

the reason want manually handle pkcs 5/7 paddings on java card in event pkcs5 ciphers not available somehow fallback method.

there no such thing hexadecimal byte. in java byte consists of 8 bits. when viewed number these bits contain 8 bit two-complement number -128 127. hexadecimals textual representation of values - such java byte - human consumption.

integers not supported on java card classic, i'll show how convert short values bytes.

if sure short s contains byte in lower 8 bits conversion simple:

byte b = (byte) s; 

if not sure must decide if want allow. if care 8 lower bits: see above.

if want have positive number 0..255 stored in byte, can check using:

if (s < 0 || s > byte_max_unsigned) {     // nasty } byte b = (byte) s; 

or negative values -128 127:

if (s < byte_min || s > byte_max) {     // nasty } byte b = (byte) s; 

of course values of constants is:

private static final short byte_max = 0x7f; private static final short byte_min = -0x80; private static final short byte_max_unsigned = 0xff; 

if keep them private static final these constants inlined bytecode converter.

as can see final byte encoding identical both cases. why two-complement default encoding in every computer on planet.

note regardless of value of short, byte hold value -128 127. if want convert byte positive value calculations, can use:

short s = b & byte_max_unsigned; 

to positive value 0 255.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -