Character encoding 如何将8位字节转换为6位字符?
我有一个特殊的要求,将字节流转换成字符编码,每个字符恰好是6位Character encoding 如何将8位字节转换为6位字符?,character-encoding,Character Encoding,我有一个特殊的要求,将字节流转换成字符编码,每个字符恰好是6位 Here's an example: Input: 0x50 0x11 0xa0 Character Table: 010100 T 000001 A 000110 F 100000 SPACE Output: "TAF " Logically I can understand how this works: Taking 0x50 0x11 0xa0 and showing as binary: 01010000
Here's an example:
Input: 0x50 0x11 0xa0
Character Table:
010100 T
000001 A
000110 F
100000 SPACE
Output: "TAF "
Logically I can understand how this works:
Taking 0x50 0x11 0xa0 and showing as binary:
01010000 00010001 10100000
Which is "TAF ".
以编程方式(伪代码或c++)执行此操作的最佳方法是什么。谢谢大家! 那么,每3个字节,就有4个字符。因此,首先,如果输入不是三个字节的倍数,您需要知道该怎么做。(它有类似base64的填充物吗?) 然后我可能会依次取3个字节。在C#中,它与C的伪代码非常接近:)
for(int i=0;i>2;
//字节i的底部2位,字节i+1的顶部4位
int value2=((数组[i]&0x3)>4);
//字节i+1的底部4位,字节i+2的顶部2位
int value3=((数组[i+1]&0xf)>6);
//字节i+2的底部6位
int value4=数组[i+2]&0x3f;
//现在使用value1…value4,例如将它们放入char数组。
//您需要将6位数字(0-63)解码为字符。
}
以防万一,如果有人感兴趣-另一个变体,它从流中提取6位数字,只要它们出现在那里。也就是说,即使当前读取的字节少于3个,也可以获得结果。将对未添加的流有用
代码将累加器a
的状态保存在变量n
中,该变量存储了上次读取时累加器中剩余的位数
int n = 0;
unsigned char a = 0;
unsigned char b = 0;
while (read_byte(&byte)) {
// save (6-n) most significant bits of input byte to proper position
// in accumulator
a |= (b >> (n + 2)) & (077 >> n);
store_6bit(a);
a = 0;
// save remaining least significant bits of input byte to proper
// position in accumulator
a |= (b << (4 - n)) & ((077 << (4 - n)) & 077);
if (n == 4) {
store_6bit(a);
a = 0;
}
n = (n + 2) % 6;
}
int n=0;
无符号字符a=0;
无符号字符b=0;
while(读取字节和字节)){
//将输入字节的(6-n)最高有效位保存到正确位置
//在蓄电池中
a |=(b>>(n+2))和(077>>n);
存储6bit(a);
a=0;
//将输入字节的剩余最低有效位保存到适当的位置
//蓄能器中的位置
a |=(b好东西,谢谢。为了回答你的问题,万一你想知道……它总是被填充。有人考虑过问相反的问题吗?
int n = 0;
unsigned char a = 0;
unsigned char b = 0;
while (read_byte(&byte)) {
// save (6-n) most significant bits of input byte to proper position
// in accumulator
a |= (b >> (n + 2)) & (077 >> n);
store_6bit(a);
a = 0;
// save remaining least significant bits of input byte to proper
// position in accumulator
a |= (b << (4 - n)) & ((077 << (4 - n)) & 077);
if (n == 4) {
store_6bit(a);
a = 0;
}
n = (n + 2) % 6;
}