我有一个练习,我必须在命令行给出的位级别上对字符串进行编码和解码。
需要注意的是,我必须使用置换映射来重新排序位。
下面是一个例子:
用户输入要编码的字符
H
H的二进制数是
01001000
但是,这是8位到0-7的常规映射。
我的程序必须将这些位转换成我使用的任何映射模式。
例如,如果我使用映射64752031
字符“H”的位
01001000
转向
01000001
编码字符时,第0位变为第6位,第2位变为第4位,第3位变为第7位,依此类推。基于地图的东西。
有没有一种方法可以根据给定的排列图来操作和更改位的顺序?
谢谢您。
最佳答案
如果需要处理大型字符串,最好使用将预计算转换的查找表。
#include <stdio.h>
unsigned char perm[256]; // permutation table
unsigned mapping[8]={6,4,7,5,2,0,3,1};
// assumes 7 6 5 4 3 2 1 0
// => 6 4 7 5 2 0 3 1
void mkperm(unsigned char perm[256]) {
for (int i=0; i<256; i++)
perm[i]=0;
for (int i=0;i<256;i++) {
for (int j=7; j>=0; j--) {
int pos=mapping[7-j]; // at mapping[0] is the new position of bit 7
if (i & (1<<j)) // only considers set bits, the table is previously cleared
perm[i] |= (1<<pos) ;
}
}
}
int main() {
mkperm(perm);
printf("%.2x => %.2x\n",'H',perm['H']);
}
mkperm()
通过扫描每个字符的连续位来计算置换表。如果在char i中设置了一个位,我们在翻译表中的位置i设置一个位,其逻辑权重由映射给定。通过将单元格i的内容用适当移位的1进行oring来设置此值。