gpt4 book ai didi

C - 将时间戳(uint_32)转换为base64

转载 作者:行者123 更新时间:2023-11-30 16:30:55 25 4
gpt4 key购买 nike

对于一些物联网通信,我需要通过短信传输一些信息,其中一些时间戳精确到秒,为了节省尽可能多的空间,我想将它们编码为base64

如何在 C 中做到这一点? (如果可能的话,无需 malloc)

(当然,我很高兴听到是否有更有效的、“无需太自定义”的方法以符合 SMS 的方式对 int32 进行编码)

最佳答案

目前我想出了这个

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);
}

请注意,它并不完全有效,因为它缺少用于填充的 ==,但在 python 中可以做到

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

它会起作用(即使已经有一些填充),这是一个很好的权衡,可以减少 25% 的空间。

关于C - 将时间戳(uint_32)转换为base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50844834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com