您的位置:首页 > 编程语言 > C语言/C++

位运算

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

//取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*/


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 数据