3

How do i explain this code to a class of Java Card Beginners in a way they will understand it perfectly:

private void getBalance(APDU apdu) {
    byte[] buffer = apdu.getBuffer();

    // inform system that the applet has finished
    // processing the command and the system should
    // now prepare to construct a response APDU
    // which contains data field
    short le = apdu.setOutgoing();

    if (le < 2) {
        ISOException.throwIt((byte) 0x6A86);
    }

    // informs the CAD the actual number of bytes
    // returned
    apdu.setOutgoingLength((byte) 2);

    // move the balance data into the APDU buffer
    // starting at the offset 0
    buffer[0] = (byte) (balance >> 8);

    buffer[1] = (byte) (balance & 0xFF);//How do i explain what happens here



    // send the 2-byte balance at the offset
    // 0 in the apdu buffer
    apdu.sendBytes((short) 0, (short) 2);
}
Belvi Nosakhare
  • 3,107
  • 5
  • 32
  • 65
  • 5
    I don't think you even need the `& 0xFF` here. – user2357112 Jan 25 '14 at 06:25
  • @user2357112: Indeed not. – T.J. Crowder Jan 25 '14 at 06:30
  • `(byte) 0x6A86` - what the heck? That looks a lot like a bug. Half the magic number is just thrown away. – user2357112 Jan 25 '14 at 06:31
  • 2
    Tell them to google bitwise operation on the internet? I mean, the [wikipedia entry](http://en.wikipedia.org/wiki/Bitwise_operation#AND) does a pretty good job of explaining it if you can't. – Brian Roach Jan 25 '14 at 06:33
  • 5
    it is javacard and because of the targeted platform, strings, int, long and some datatype are not supported, only short and byte data type is supported, so that is why there is a lot of casting to byte in the code – Belvi Nosakhare Jan 25 '14 at 06:40
  • 1
    Still that `ISOException.throwIt((byte) 0x6A86);` sould certainly be `ISOException.throwIt((short) 0x6A86);` – Michael Roland Jan 25 '14 at 09:26
  • You don't need to pass APDU anymore, there is a static method for that. Explain that Le should really be Ne in Java Card. Fix the ISO exception issue from Michael, and explain that `throwIt()` has control flow issues (it is not seen as an exit point). Explain that the status word is not correct. Explain that it is better to use an `offset` instead of constant values, call `apdu.setOutgoingLength()` later and use `Util.setShort()` instead of doing those shifts etc. In other words, fix your code before you start explaining it. – Maarten Bodewes Jan 27 '14 at 13:43

1 Answers1

1

Explain binary representation of integers. Explain the >> shift operator. Explain hexidecimal notation, and what 0xFF becomes. Explain bitwise and/or operators. Put it all together to show how the combination of >>8 and &0xFF breaks a 16-bit value into high and low bytes. Ask if there are any questions.

keshlam
  • 7,931
  • 2
  • 19
  • 33