如何将普通 int 转换为 12 位长的二进制代码,然后使用 Base64 将其转换为 2 个字母?

问题描述 投票:0回答:1

我有多个正整数,它们都包含可以用 12 位或更少位表示的数字。我需要将每个整数的每个值转换为 12 位二进制代码,然后将每个 12 位二进制代码分成 2 个相等的部分,并使用 base64 编码将每个部分(每个部分长 6 位)转换为符号。

示例 - 假设我有这个: 整数a = 2572; 2572 的二进制代码是 101000001100。 现在我将 101000001100 分成 2 部分,每部分 6 位: 101000 和 001100 然后我使用 base64 将每个部分转换为符号,然后剩下 oM,我想打印它。

或者如果我有: 整数a = 172 172 在二进制代码中是 10101100,这是 8 位,所以现在我添加额外的 4 个零,使其成为 12 位,同时保留值 (172):000010101100 然后分为两部分: 000010 101100 并将每个转换为具有 base64 的符号。

我希望你能明白,我只能看到很长的路要走,但我想知道是否其他人已经做过这样的事情,或者它是否比我想象的更容易。预先感谢

c base64 bit
1个回答
0
投票

最简单的方法之一是使用按位运算。在这种情况下,需要按位与 (&) 和右移位 (>>)。

备注

  • 为了清楚起见,这些位按 6 个一组进行分组。
  • 为了便于阅读,省略了前导零。

按位与的简短解释

按位与比较两个位。当且仅当输入的两个位均为 1 时,结果位才为 1。 问题示例:

按位与

a =         101000 001100
                   111111
firstPart =        001100
a =          101000 001100
             111111 000000
secondPart = 101000 000000

firstPart 现在是所需的值。然而,第二部分的位必须向右移动 6 位,然后删除末尾的 6 位并在开头添加 6 个零:

位移位

secondPart = 101000 000000
shift: =            101000 000000
result: =    000000 101000

更多信息和解释可以在互联网上找到(例如wikipedia)。

示例代码

#include <stdio.h>
#include <inttypes.h>

int main() {
    
    /* integers are positive, so use unsigned int*/
    unsigned int a = 2572;
    
    /*
    First take the last 6 bits by performing bitwise and. 
    This results in 'firstPart' being equal to the last 6 bits of a.
    */
    int64_t firstPart = a & 0b111111;
    printf("firstPart = %" PRIi64 "\n", firstPart);
    
    
    /* 
    Secondly, taking the next 6 bits in the same way and 
    shifting them to the right. This results in 'secondPart'
    being equal to the second last 6 bits of a.
    */
    int64_t secondPart = a & 0b111111000000;
    secondPart >>= 6;
    printf("secondPart = %" PRIi64 "\n", secondPart);
    
}
© www.soinside.com 2019 - 2024. All rights reserved.