@Override
  public void format(ByteArrayOutputStream buf) {
    if (buf == null) {
      return;
    }

    // Text string object
    int tag = 0x80 | ComprehensionTlvTag.TEXT_STRING.value();
    buf.write(tag); // tag

    byte[] data;

    if (mIsYesNo) {
      data = new byte[1];
      data[0] = mYesNoResponse ? GET_INKEY_YES : GET_INKEY_NO;
    } else if (mInData != null && mInData.length() > 0) {
      try {
        // ETSI TS 102 223 8.15, should use the same format as in SMS messages
        // on the network.
        if (mIsUcs2) {
          // ucs2 is by definition big endian.
          data = mInData.getBytes("UTF-16BE");
        } else if (mIsPacked) {
          byte[] tempData = GsmAlphabet.stringToGsm7BitPacked(mInData, 0, 0);
          // The size of the new buffer will be smaller than the original buffer
          // since 7-bit GSM packed only requires ((mInData.length * 7) + 7) / 8 bytes.
          // And we don't need to copy/store the first byte from the returned array
          // because it is used to store the count of septets used.
          data = new byte[tempData.length - 1];
          System.arraycopy(tempData, 1, data, 0, tempData.length - 1);
        } else {
          data = GsmAlphabet.stringToGsm8BitPacked(mInData);
        }
      } catch (UnsupportedEncodingException e) {
        data = new byte[0];
      } catch (EncodeException e) {
        data = new byte[0];
      }
    } else {
      data = new byte[0];
    }

    // length - one more for data coding scheme.

    // ETSI TS 102 223 Annex C (normative): Structure of CAT communications
    // Any length within the APDU limits (up to 255 bytes) can thus be encoded on two bytes.
    // This coding is chosen to remain compatible with TS 101.220.
    // Note that we need to reserve one more byte for coding scheme thus the maximum APDU
    // size would be 254 bytes.
    if (data.length + 1 <= 255) {
      writeLength(buf, data.length + 1);
    } else {
      data = new byte[0];
    }

    // data coding scheme
    if (mIsUcs2) {
      buf.write(0x08); // UCS2
    } else if (mIsPacked) {
      buf.write(0x00); // 7 bit packed
    } else {
      buf.write(0x04); // 8 bit unpacked
    }

    for (byte b : data) {
      buf.write(b);
    }
  }