请看一下下面的 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 Card 中,APDU 缓冲区 header 字段被视为有符号字节。所以我认为响应 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
问题出在其他地方。
可能值得注意的是 (byte) 0x80
导致 -128
。
关于java - Java/Java Card中的"Switch Case"和"If...else.."区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523941/