Tuesday, September 6, 2011

GSM 7bit (part of PDU) pack/encoding algorithm in Java

GSM 7bit (part of PDU) pack/encoding algorithm in Java. This can be used for SMS/USSD writing.


public static String stringTo7bit(String string) {
        String hex = "";
        byte[] bytes = string.getBytes();
        int f = 0;
        while (f < bytes.length - 1) {
            int t = (f % 8) + 1;
            if (t < 8) {
                byte b = (byte) (((bytes[f] >>> (t - 1)) |
                    (bytes[f + 1] << (8 - t))) & 0x000000FF);
                hex += intToHex(b & 0x000000FF).toUpperCase();
            }
            f++;
        }
        if ((f % 8) + 1 < 8)
            hex += intToHex((bytes[f] >>> (f % 8)) & 0x000000FF).toUpperCase();
        return hex;
    }
public static String intToHex(int i) {
        String hex = Integer.toHexString(i);
        if (hex.length() % 2 != 0) hex = 0 + hex;
        return hex;
    }

highlighted with: http://tohtml.com/

4 comments:

  1. Nikolay, thanks, do you have the same for decoding, i.e. PDu to String?

    ReplyDelete
    Replies
    1. Hello,

      Unfortunately, I don't have reverse transformation function (7bit PDU to String). In my case I had GSM modem and the only thing I had to do is create String to PDU converter. Opposite transformation was implemented in modem.

      Thank you!

      Delete
  2. Thanks Nikolay...This code saved my day !!!

    ReplyDelete
    Replies
    1. Hello Ani,

      You're welcome! I'm very glad it was useful.

      Thank you!

      Delete