以BCD(16进制)码存储的Char数据以Int型表示
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");
}
补充:软件开发 , C++ ,