新聞詳情
單片機(jī)開發(fā)十進(jìn)制和十六進(jìn)制轉(zhuǎn)換瀏覽數(shù):305次
單片機(jī)設(shè)計中經(jīng)常需要用到十進(jìn)制和十六進(jìn)制,他們之間轉(zhuǎn)換如下。 #include <reg51.h> #include <intrins.h> #include <stdio.h> #include <ctype.h> #define LongToBin(n) \ ((n >> 21) & 0x80) | \ ((n >> 18) & 0x40) | \ ((n >> 15) & 0x20) | \ ((n >> 12) & 0x10) | \ ((n >> 9) & 0x08) | \ ((n >> 6) & 0x04) | \ ((n >> 3) & 0x02) | \ ((n ) & 0x01) \ ) #define Bin(n) LongToBin(0x##n##l) // HEX轉(zhuǎn)BCD //bcd_data(<0x255,>0) unsigned char BCD2HEX(unsigned int bcd_data) { unsigned char temp; temp=((bcd_data>>8)*100)|((bcd_data>>4)*10)|(bcd_data&0x0f); return temp; } // HEX轉(zhuǎn)BCD //hex_data(<0xff,>0) unsigned int HEX2BCD(unsigned char hex_data) { unsigned int bcd_data; unsigned char temp; temp=hex_data%100; bcd_data=((unsigned int)hex_data)/100<<8; bcd_data=bcd_data|temp/10<<4; bcd_data=bcd_data|temp%10; return bcd_data; } void main(void) { unsigned int c; c= Bin(10101001); // c = 0xA9 c=BCD2HEX(0x255); //255 轉(zhuǎn)成HEX為0xff c=HEX2BCD(0xff); //0xff 轉(zhuǎn)成BCD碼為 255 } |