给定三个字符串输入a,b,c,如何将这三个8位值转换为一个24位值。接下来,我如何将该24位值转换为四个独立的6位值。
例如:
a = ascii' A' = 0x41 = 0100 0001
b = ascii' B' = 0x42 = 0100 0010
c = ascii' C' = 0x43 = 0100 0011
allTogether = 010000010100001001000011
sixBit1 = 010000
sixBit2 = 010100
sixBit3 = 001001
sixBit4 = 000011
现在为了实现,我正在考虑将allTogether设为一个int,因为它可以容纳32位,然后将chars转换为A' B' B'和' C'离开了int,但我不确定要向左转移多少。至于获得四个六位值,我不知道如何做到这一点,我不知道我应该使用什么数据类型。任何帮助表示赞赏!
答案 0 :(得分:-1)
实施类似于以下
unsigned int a = 'A'; // = 0x41 = 0100 0001
unsigned int b = 'B'; // = 0x42 = 0100 0010
unsigned int c = 'C'; // = 0x43 = 0100 0011
unsigned int allTogether = 0 // 010000010100001001000011
unsigned int sixBit1 = 0; // 010000
unsigned int sixBit2 = 0; // 010100
unsigned int sixBit3 = 0; // 001001
unsigned int sixBit4 = 0; // 000011
allTogether = (a<<16)||(b<<8)||c;
sizbit1 = (allTogether&0x00FC0000)>>18;
sizbit2 = (allTogether&0x0003F000)>>12;
sizbit3 = (allTogether&0x00000FC0)>>6;
sizbit4 = (allTogether&0x0000003F);
答案 1 :(得分:-1)
试试这个:
#include <stdint.h>
int main (int argc, char const *argv[])
{
char c1, c2, c3;
c1 = 'A';
c2 = 'B';
c3 = 'C';
uint32_t allTogether = c1 << 16 | c2 << 8 | c3;
uint32_t sixBit1 = (allTogether & (0b111111 << 18)) >> 18;
uint32_t sixBit2 = (allTogether & (0b111111 << 12)) >> 12;
uint32_t sixBit3 = (allTogether & (0b111111 << 6)) >> 6;
uint32_t sixBit4 = (allTogether & 0b111111);
return 0;
}
请注意,0b111111
是由GCC和LLVM支持的二进制文字,可能还有一些其他编译器,但不是所有编译器。如果您的编译器不支持它,请替换为127
。