C-使用移位运算符进行基本转换 [英] C - Using bit-shift operators for base conversion
问题描述
我正在尝试在C语言中将一些数据从十六进制转换为base64,我在线找到了一种算法,但我真的很想知道它是如何工作的,而不是仅仅强加于人并激发它.如果有人可以解释下面的工作方式,我将不胜感激.我一直在阅读有关移位运算符的信息,但似乎不像我想象的那样了解它们……对我来说,点击并不算是很容易.
I'm trying to convert some data from hex to base64 in C, I found an algorithm online but I would really like to know how it works rather than just implenting it and firing it off. If someone could please explain how the following is working I would appreciate it. I have been reading about the shift operators and I don't seem to understand them as much as I thought I did...it's not quite clicking for me.
for (x = 0; x < dataLength; x += 3)
{
/* these three 8-bit (ASCII) characters become one 24-bit number */
n = data[x] << 16;
if((x+1) < dataLength)
n += data[x+1] << 8;
if((x+2) < dataLength)
n += data[x+2];
/* this 24-bit number gets separated into four 6-bit numbers */
n0 = (uint8_t)(n >> 18) & 63;
n1 = (uint8_t)(n >> 12) & 63;
n2 = (uint8_t)(n >> 6) & 63;
n3 = (uint8_t)n & 63;
此代码取自Wikibooks,这不是我的,我只是想了解位偏移及其如何使我转换数据.
This code was taken from Wikibooks, it is NOT mine, I'm just trying to understand the bitshifting and how it's allowing me to convert the data.
非常感谢您的帮助.
来源: Base64
推荐答案
首先,输入数据不是您所说的十六进制.它只是将数据存储为字节.该代码将为您提供base64表示(尽管您发布的代码缺少将n0
,n1
,n2
,n3
映射到可打印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
这篇关于C-使用移位运算符进行基本转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!