C - convert a timestamp (uint_32) into base64

allan.simon Source

For some IoT communication I need to transmit some information over SMS, some of them being timestamp precise to the seconds, in order to save as much place as possible, I would like to encode them in base64

How to do this in C ? (if possible without malloc)

(of course I'm glad to hear if there's a more efficient, "no too custom" method of encoding an int32 in a SMS-compliant way)

cbase64iot

Answers

answered 1 week ago allan.simon #1

For the moment I came up with this

void base64_encode_timestamp(
    uint32_t timestamp,
    char encoded_data[6]
) {

    // 26 because we encode 6 bits by 6, and it's a 32 bits integer
    // so  32 - 6 = 26
    // and & 0x3F is a mask for 0b111_111
    encoded_data[0] = encoding_table[(timestamp >> 26) & 0x3F];
    encoded_data[1] = encoding_table[(timestamp >> 20) & 0x3F];
    encoded_data[2] = encoding_table[(timestamp >> 14) & 0x3F];
    encoded_data[3] = encoding_table[(timestamp >> 8) & 0x3F];
    encoded_data[4] = encoding_table[(timestamp >> 2) & 0x3F];
    // here << 4 is actually ">> -2" because we have 2 bits remaining
    // that we need to pad with four '0' 
    encoded_data[5] = encoding_table[(timestamp << 4) & 0x3F];
}

// a main to show that it works
int main() {

    // Wednesday, 13-Jun-18 09:56:27 UTC
    uint32_t timestamp = 1528883787;
    char timestamp_base64[6] = {};
    base64_encode_timestamp(timestamp, timestamp_base64);
    printf("%.6s\n", timestamp_base64);
}

note that it's not exactly valid as it's missing the == for padding, but in python one can do

(my_string + '===').decode('base64')

and it will works (even if there's already some padding) , which is a good tradeoff for a 25% decrease in space.

comments powered by Disqus