如何在Java Card中将整数转换为二进制字符?

时间:2013-03-09 20:07:38

标签: javacard

如何在Java Card中将字节数组转换为二进制数组以获得10101010的结果?

RandomData random_data =
  RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
// the seed is supplied in the byte array seed
random_data.setSeed(sseed, seed_offset, seed_length);
// a random number is written into the byte array random_num
random_data.generateData(random_num, random_num_offset,
                         random_num_length);

1 个答案:

答案 0 :(得分:1)

字节数组已经是一组位的二进制表示(就像这个问题的短数组一样)。与位数组的唯一区别在于,您将始终获得8位组中的位,并且无需执行某些按位操作就无法单独寻址每个位。

通常,String(一段文本)中的位表示不在卡上执行。在将比特发送到终端上的应用程序之后执行。您可能已经注意到Java Card classic上缺少String类型。


根据要求,将bitjes(荷兰语中的位)转换为Java Card字符的方法。谢谢你的谜题。

/**
 * Converts an array of bytes, used as a container for bits, into an ASCII
 * representation of those bits.
 * 
 * @param in
 *            the input buffer
 * @param inOffset
 *            the offset of the bits in the input buffer
 * @param bitSize
 *            the number of bits in the input buffer
 * @param out
 *            the output buffer that will contain the ASCII string
 * @param outOffset
 *            the offset of the first digit in the output buffer
 * @return the offset directly after the last ASCII digit
 */
public static final short toBitjes(final byte[] in, short inOffset,
        final short bitSize, final byte[] out, short outOffset) {
    for (short i = 0; i < bitSize; i++) {
        final byte currentByte = in[inOffset + i / BYTE_SIZE];
        out[outOffset++] = (byte) (0x30 + ( (currentByte >> (7 - (i % BYTE_SIZE))) & 1 ) );
    }
    return outOffset;
}

当然可以随意重命名“bitjes”。


用法:

// buffer containing 9 bits valued 10011001.1 in middle of buffer
final byte[] inBuffer = new byte[] { 0x00, (byte) 0x99, (byte) 0x80, 0x00 };
final short bitSize = 9;
// bit array starting at byte 1 
final short inOffset = 1;

// or use JCSystem#makeTransientByteArray()
final byte[] outBuffer = new byte[40];
// ASCII start at offset 2
final short outOffset = 2;

// newOffset will be 2 + 9 = 11
short newOffset = toBitjes(inBuffer, inOffset, bitSize, outBuffer, outOffset);