Java / Java卡中“ Switch Case”和“ If … else ..”的区别
作者:互联网
请查看以下Java Card程序.它们在逻辑上看似平等,但在实践中却有不同的输出:
使用switch … case的简单传入APDU命令分析器:
package testPack;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
public class TestApp extends Applet {
private TestApp() {
}
public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException {
new TestApp().register();
}
public void process(APDU arg0) throws ISOException {
if (selectingApplet()) {
return;
}
byte[] buffer = arg0.getBuffer();
byte ins = buffer[ISO7816.OFFSET_INS];
switch (ins) {
case (byte) 0x80:
ISOException.throwIt((short) 0x6901);
break;
default:
ISOException.throwIt((short) 0x6902);
break;
}
}
}
同一程序使用if … else …:
package testPack;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
public class TestApp extends Applet {
private TestApp() {
}
public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException {
new TestApp().register();
}
public void process(APDU arg0) throws ISOException {
if (selectingApplet()) {
return;
}
byte[] buffer = arg0.getBuffer();
byte ins = buffer[ISO7816.OFFSET_INS];
if (ins == (byte) 0x80) {
ISOException.throwIt((short) 0x6901);
} else {
ISOException.throwIt((short) 0x6902);
}
}
}
众所周知,在Java卡中,APDU缓冲区标头字段被视为带符号的字节.因此,我认为响应00 80 00 00 00 APDU命令,以上两个程序都必须收到69 02.
但这是结果:
第一个程序:
Download Cap begin...
Download Cap successful.
Install Applet begin...
Install Applet successful.
Select Applet begin...
Select Applet successful.
Send: 00 80 00 00 00
Recv: 69 01
第二程序:
Download Cap begin...
Download Cap successful.
Install Applet begin...
Install Applet successful.
Select Applet begin...
Select Applet successful.
Send: 00 80 00 00 00
Recv: 69 02
为什么反应不同?
解决方法:
Java没有错.这段代码:
byte ins = (byte) 0x80;
switch (ins) {
case (byte) 0x80:
System.out.println("switch matched");
break;
default:
System.out.println("switch missed");
}
if (ins == (byte) 0x80) {
System.out.println("if matched");
} else {
System.out.println("if missed");
}
产生:
switch matched
if matched
问题出在别的地方.
可能值得注意的是(字节)0x80导致-128.
标签:javacard,java 来源: https://codeday.me/bug/20191119/2032823.html