unsigned int 与 字符串 之间相互转换

最近项目中要用到邀请码之类的东西,但是又想跟玩家KEY关联起来,所以干脆自己简单写了个小玩意。

代码:

/**
 * @author  nhpeng,nhpeng1104@gmail.com
 * @date    2015/07/16 14:27:11 CST
 * @brief   
 *
 * 
 */
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;

const char dst[66] = "#@$abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const unsigned short int k = 65; 

void uint32_to_str(unsigned int x, char *s) 
{
    unsigned short int k0 = x >> 24; 
    unsigned short int k1 = (x >> 16) & 0xff;
    unsigned short int k2 = (x >> 8) & 0xff;
    unsigned short int k3 =  x & 0xff;
    s[0] = dst[k0%k];
    s[1] = dst[k1%k];
    s[2] = dst[( k0/k + k1/k*10 + k2/k*100 + k3/k*1000 ) / k] ;
    s[3] = dst[( k0/k + k1/k*10 + k2/k*100 + k3/k*1000 ) % k] ;
    s[4] = dst[k2%k];
    s[5] = dst[k3%k];
    s[6] = '\0';
    cout << s << endl;
}

void str_to_uint32(unsigned int &x, const char *s) 
{
    unsigned int m = ( strchr(dst,s[2]) - dst ) * k +  ( strchr(dst,s[3]) - dst );
    unsigned int i = ( strchr(dst,s[0]) - dst ) + m % 10 * k , total = 0;
    total += i << 24; 
    i = ( strchr(dst,s[1]) - dst ) + m % 100 / 10 * k;
    total += i << 16; 
    i = ( strchr(dst,s[4]) - dst ) + m % 1000 / 100 * k;
    total += i << 8;
    i = ( strchr(dst,s[5]) - dst ) + m / 1000 * k;
    total += i;
    cout << total << endl;
}

int main()
{
    char s[7];
    unsigned int m_src = 3827889388,m_dst = 0;
    cout << m_src << endl;
    uint32_to_str(m_src,s);
    str_to_uint32(m_dst,s);

    return 0;
}

输出:
3827889388
4BLOKC
3827889388

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值