且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C-使用移位运算符进行基本转换

更新时间:2023-02-10 18:58:34

首先,输入数据不是您所说的十六进制.它只是将数据存储为字节.该代码将为您提供base64表示(尽管您发布的代码缺少将n0n1n2n3映射到可打印ASCII字符的部分).

First of all, the input data is not hex as you say. It's simply data stored as bytes. The code will give you the base64 representation of it (although the code you posted lacks the part which will map n0, n1, n2, n3 to printable ASCII characters).

假设输入的前三个字节为(以二进制表示,每个字母代表0或1):

Suppose the first three bytes of the input are (in binary representation, each letter represents a 0 or 1):

abcdefgh, ijklmnop, qrstuvwx

代码的第一部分将它们组合为单个24位数字.这是通过将第一个16位左移,第二个8位左移并添加:

The first part of the code will combine them to a single 24-bit number. This is done by shifting the first one 16 bits to the left and the second one 8 bits to the left and adding:

  abcdefgh0000000000000000      (abcdefgh << 16)
+ 00000000ijklmnop00000000      (ijklmnop << 8)
  0000000000000000qrstuvwx
  ------------------------
  abcdefghijklmnopqrstuvwx

然后通过移位和与将其分成四个6位数字.例如,第二个数字是通过向右移12位并加上111111来计算的.

Then it separates this into four 6-bit numbers by shifting and and'ing. For example, the second number is calculated by shifting 12 bits to the right and and'ing with 111111

n     =   abcdefghijklmnopqrstuvwx

n>>12 =   000000000000abcdefghijkl
63    =   000000000000000000111111

And'ing gives:
          000000000000000000ghijkl