我有一个输出12位值的ADC,每个位用真或假表示。如何将其转换为int?
例如:
12位值为111111000001
//getLevel returns true or false
boolean bit0 = getLevel(channel0);//true
boolean bit1 = getLevel(channel1);//true
boolean bit2 = getLevel(channel2);//true
boolean bit3 = getLevel(channel3);//true
boolean bit4 = getLevel(channel4);//true
boolean bit5 = getLevel(channel5);//true
boolean bit6 = getLevel(channel6);//false
boolean bit7 = getLevel(channel7);//false
boolean bit8 = getLevel(channel8);//false
boolean bit9 = getLevel(channel9);//false
boolean bit10 = getLevel(channe10);//false
boolean bit11 = getLevel(channe11);//true
///do something to convert bit0 - bit11 to an int == 4033
任何想法如何解决这个问题?
答案 0 :(得分:1)
将位存储在BitSet中。
BitSet bits = new BitSet();
//set the bit fields...
//convert bitset to integer
int bitInteger = 0;
for(int i = 0 ; i < bits.length(); i++) {
if(bits.get(i)) {
bitInteger |= (1 << i); //logical OR each bit into the integer and shift left
}
}