char型數據裡面的數據是以16進制數存儲的,每個char型數據的可能值是從0x00~0xff(表示為2進制范圍是從00000000~11111111)的16進制數,即每個char型數據裡面能存儲8位的數據。如果存儲類型為BCD碼,那也就是按照2進制來存儲數據。對應表如下:
[cpp]
Int 二進制 BCD碼 Hex
0 0000 0000 0
1 0001 0001 1
2 0010 0010 2
3 0011 0011 3
4 0100 0100 4
5 0101 0101 5
6 0110 0110 6
7 0111 0111 7
8 1000 1000 8
9 1001 1001 9
10 1010 1010 A
11 1011 1011 B
12 1100 1100 C
13 1101 1101 D
14 1110 1110 E
15 1111 1111 F
實現轉換的代碼如下:
[cpp]
#include<iostream>
#include<time.h>
using namespace std;
string Char2BCD(unsigned char *c,int len)
{
char s[100];
char c1,c2;
string str="";
for(int i=0;i<len;i++)
{
c1= c[i]&0x0f;//提取2進制數的低4位
c2= c[i]>>4;//提取2進制數的高4位
int n=c2*10+c1;//轉成int(10進制數)表示
//int n=(int)(((c2&0x08+c2&0x04+c2&0x02+c2&0x01)<<4)+(c1&0x08+c1&0x04+c1&0x02+c1&0x01));
if(n<=9&&n>=0)
{
str+="0";
}
str+=itoa(n,s,10);
}
return str;
}
int main(){
char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep); /*取得當地時間*/
printf ("%d %d %d ", (1900+p->tm_year),( 1+p->tm_mon), p->tm_mday);
printf("%s %d:%d:%d\n", wday[p->tm_wday],p->tm_hour, p->tm_min, p->tm_sec);
int tt=(p->tm_year-100);
unsigned char cc=(((tt/10)&0x0f)<<4)+((tt%10)&0x0f);
cout<<"YY: "<<Char2BCD(&cc,1)<<endl;
cout<<"INT: "<<0x17<<endl;//16進制的0x17是10進制(即int型)的23
unsigned char c=0x17;
cout<<"BCD: "<<Char2BCD(&c,1)<<endl;
unsigned char a[4]={0x17,0x99,0x99};
cout<<"ID "<<Char2BCD(a,3)<<endl;
system("pause");
}