你肯定在正确的轨道上。这是一些充实的代码,它将 a 的前四位或后四位增加int
给定的数量。
请注意,我int
在这里使用而不是byte
. 即使您的数据是 a byte
,通常也更容易将其作为int
. 这是因为java 按位运算符喜欢|
and&
和<<
return int
。因此,一旦您完成了所有的操作,最容易使用您的数据作为int
然后回退。
此外,如果您需要在每位级别上处理大量数据(可能不仅仅是您提到的两个计数器),您可能会考虑查看BitSet。
public class Test {
public static void main(String[] args)
{
int counter = 0;
// increment the low bits by 3 and high bits by 2
counter = addLowBits( counter, 3 );
counter = addHighBits( counter, 2 );
// print the hex string to verify
System.out.println( Integer.toHexString( counter ) );
System.out.println( "Low Counter: " + ( counter & 0x0F ) );
System.out.println( "High Counter: " + ( ( counter & 0xF0 ) >> 4 ) );
}
public static int addLowBits( int counter, int increment )
{
// get the low bits
int low = counter & 0x0F;
// increment by 1
low = low + increment;
// mask the high bits and insert new low bits
counter = (counter & 0xF0) | low;
return counter;
}
public static int addHighBits( int counter, int increment )
{
// now get high bits
int high = ( counter & 0xF0 ) >> 4;
// increment by 1
high = high + increment;
// mask the low bits and insert new high bits
counter = (counter & 0x0F) | ( high << 4 );
return counter;
}
}