位运算

来源:互联网 发布:网络教育文凭国家承认吗 编辑:程序博客网 时间:2024/05/17 16:43

在嵌入式发开中经常用到 <<(左移) >>(右移)运算符,一般用于取某个字节的第几位,下面总结一下:


//取temp中某一位的值
BYTE cByye[8] = {0};
char temp = 0x11;
cByye[0] = temp >>0 &1;
cByye[1] = temp >>1 &1;
cByye[2] = temp >>2 &1;
cByye[3] = temp >>3 &1;
cByye[4] = temp >>4 &1;
cByye[5] = temp >>5 &1;
cByye[6] = temp >>6 &1;
cByye[7] = temp >>7 &1;

//高4位和低4位取出来
int high4 = (BYTE >>4) & 0xf;
int low4 =BYTE & 0x0f;


//取高五位
int high5 = (((((BYTE >>4)&0x0f)>>0)&1)<<4)+(BYTE &0x0f);
DWORD code = 123456;
BYTE aaa,bbb,ccc;

aaa = code&0xff;
bbb = (code & 0x0000FF00)>>8;
ccc = (code & 0x00FF0000)>>16;


//多字节组成一个字节
int aaaa = 0x12;
int bbbb = 0x34;
int cccc = 0x56;
int dddd = 0x78;

int ssss = ((aaaa&0xFF)<<8)+bbbb;
int xxxx = ((aaaa&0xFF)<<24)+((bbbb&0xFF)<<16)+((cccc&0xFF)<<8)+dddd;

//十六进制字符串转十进制字符串
char temp[10] = {0x1, 0x4, 0x7, 0x8, 0x6, 0x9, 0x5, 0x2, 0x0, 0x2};
char dst[16];
int nLen=strlen(temp);
for (int i=0; i<10; ++i)   
{
    sprintf(dst,"%s%X", dst, temp[i]);  
}


DWORD aaa = atol(dst); // 0x58231922
BYTE byte_byte[8] = {0};

byte_byte[0] = (aaa & 0xf0000000)>>28;
byte_byte[1] = (aaa & 0x0f000000)>>24;
byte_byte[2] = (aaa & 0x00f00000)>>20;
byte_byte[3] = (aaa & 0x000f0000)>>16;
byte_byte[4] = (aaa & 0x0000f000)>>12;
byte_byte[5] = (aaa & 0x00000f00)>>8;
byte_byte[6] = (aaa & 0x000000f0)>>4;
byte_byte[7] = (aaa & 0x0000000f);


byte[] Time = new byte[4];
System.arraycopy(Msgbody, Msgbody.length - 4, Time, 0, 4);

int temp1 = ((Time[0]&0x0F)<<4)+Time[1];
int temp2 = ((Time[2]&0x0F)<<4)+Time[3];
int nTime = ((temp1/0x10)*10 + (temp1%0x10))*100 + (temp2/0x10)*10 + (temp2%0x10);
System.out.print("Time: " + nTime + "s");


#define HEX2BCD(x) (((x) % 10) + ((((x) / 10) % 10) << 4))  /*20 -> 20H*/

0 0