Javacard 倍增短裤

问题描述 投票:0回答:1

我正在尝试将一些 Java 代码转换为 Javacard 代码,其中我无法使用 int 或 long 类型,但我遇到了问题。 我想要转换的代码:

void someFunction(short a, short b)
{
    int x = (int)((int)a * (int)b);
}

由于 Javacard 根本不能使用整数类型,我尝试使用“multiplyShorts”函数对其进行转换,如下所示:

public static short[] multiplyShorts(short a, short b)
{
    short aHigh = (short)((a >> 8) & 0xFF);
    short aLow  = (short)(a & 0xFF);
    short bHigh = (short)((b >> 8) & 0xFF);
    short bLow  = (short)(b & 0xFF);
    short lowLow = (short)(aLow * bLow);
    short highLow = (short)(aHigh * bLow);
    short lowHigh = (short)(aLow * bHigh);
    short highHigh = (short)(aHigh * bHigh);
    short[] result = new short[2];
    result[1] = (short)(lowLow & 0xFF);
    short carry = (short)((lowLow >> 8) & 0xFF);
    short middle = (short)(highLow + lowHigh + carry);
    result[1] |= (short)((middle & 0xFF) << 8);
    result[0] = (short)((middle >> 8) & 0xFF);
    result[0] = (short)(result[0] + highHigh);
    return result;
}

此代码在大多数情况下都有效,但在 a=0xFFFF 和 b=0xFFFF 的情况下,我期望:

result[0] = 0xFFFE = 0b11111111_11111110
result[1] = 0x0001 = 0b00000000_00000001

然而,我得到的结果是:

result[0] = 0xFEFE = 0b11111110_11111110 //Spot the difference on this line
result[1] = 0x0001 = 0b00000000_00000001

有人可以解释一下我在这里缺少什么,或者为我转换代码提供任何帮助吗?

java javacard
1个回答
0
投票

使用无符号签名类型会出现问题,您必须调整每个操作。

使用

short carry = (short) ((lowLow >> 8) & 0xFF);
short t = (short) ((highLow + lowHigh)& 0xFF);
short middle = (short) (t + carry);

你会得到正确的答案。

© www.soinside.com 2019 - 2024. All rights reserved.