简体   繁体   中英

How to send value bigger than 127 in byte Java

I am working on an Smart Card where there is a method in javax.smartcardio.CommandAPDU .

CommandAPDU(int cla, int ins, int p1, int p2, byte[] data, int ne) 

I need to send data as byte[] (5th argument). Now my problem is that, as Java primitive data types are signed the max value of a byte can not exceed 127. I need to send a value bigger than 127. To be precise, the hex value 94 which is equal to 148.

As some solution suggests that we can cast it to integer.

byte b = -108;
int i = b & 0xff;

I can't do that as the CommandAPDU(); constructor doesn't take an [] . So how to do it?

Depending on how it is interpreted by the smart card, you could just send the correct negative value. If the smart card interprets value as unsigned, you could for example send -1 for 255.

You're calculating the APDU with unsigned bytes, while Java uses signed bytes.

It's just a matter of how the data is interpreted, sending -108 to the smart card will be interpreted in exactly the same way as sending 148 from a platform using unsigned bytes. The bit combination is exactly the same.

Java can even do the conversion itself so that you can write the code using unsigned numbers;

byte data = (byte)0x94;   // stores -108 in "data", which will be interpreted
                          // as 148 on an unsigned platform

For long blocks of data, it is probably best to use a hexadecimal encoder/decoder. But be sure that you handle the data as bytes internally (directly decode and don't look back to the hex String ). The Apache codec library contains a good encoder/decoder, or you can use Bouncy Castle or Guava or use one of the many examples on SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM