以BCD(16进制)码存储的Char数据以Int型表示

char型数据里面的数据是以16进制数存储的,每个char型数据的可能值是从0x00~0xff(表示为2进制范围是从00000000~11111111)的16进制数,即每个char型数据里面能存储8位的数据。如果存储类型为BCD码,那也就是按照2进制来存储数据。对应表如下:

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

实现转换的代码如下:

#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");
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值