c 语言 进制转换 短小精悍

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
int main() {
    int i,v;
    char bs[33];
    char b[33];
    char hs[9];
    char h[9];
    char s[4];
    char *e;

// 十进制整数转二进制串;
    i=1024;
    ltoa(i,b,2);
    sprintf(bs,"%032s",b);
    printf("i=%d,bs=%s\n",i,bs);
// 十进制整数转十六进制串;
    i=1024;
    ltoa(i,h,16);
    sprintf(hs,"%08s",h);
    printf("i=%d,hs=%s\n",i,hs);
// 十六进制字符串转成十进制数
    strcpy(hs,"00000400");
    sscanf(hs,"%x",&i);
    printf("hs=%s,i=%d\n",hs,i);
// 二进制字符串转化为十六进制字符串;
    strcpy(bs,"00000000000000000000010000000000");
    i=strtol(bs,&e,2);
    ltoa(i,h,16);
    sprintf(hs,"%08s",h);
    printf("bs=%s,hs=%s\n",bs,hs);
// 二进制字符串转化为十进制数;
    strcpy(bs,"00000000000000000000010000000000");
    i=strtol(bs,&e,2);
    printf("bs=%s,i=%d\n",bs,i);
// 十六进制字符串转成二进制串
    strcpy(hs,"00000400");
    sscanf(hs,"%x",&i);
    ltoa(i,b,2);
    sprintf(bs,"%032s",b);
    printf("hs=%s,bs=%s\n",hs,bs);
// ASC\GBK字符串转十六进制串
    strcpy(s,"a汉");
    i=0;
    while (1) {
        if (0==s[i]) break;
        sprintf(hs+i*2,"%02X",(unsigned char)s[i]);
        i++;
    }
    setlocale(LC_ALL,"chs");
    printf("s=%s,hs=%s\n",s,hs);
// 十六进制字符串转成汉字(GBK)及字符(ASC)
    strcpy(hs,"61BABA");
    i=0;
    while (1) {
        if (1!=sscanf(hs+i*2,"%2x",&v)) break;
        s[i]=(char)v;
        i++;
    }
    s[i]=0;
    printf("hs=%s,s=%s\n",hs,s);

    return 0;

}
//i=1024,bs=00000000000000000000010000000000
//i=1024,hs=00000400
//hs=00000400,i=1024
//bs=00000000000000000000010000000000,hs=00000400
//bs=00000000000000000000010000000000,i=1024
//hs=00000400,bs=00000000000000000000010000000000
//s=a汉,hs=61BABA
//hs=61BABA,s=a汉

 c 语言 进制转换 短小精悍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值