''1234''转化为0x12,0x34

//
// DecToHex.cpp
//

// Sample :
// unsigned char s1[8]="12345678" Cast to unsigned char s2[4]={0x12,0x34,0x56,0x78}
// unsigned char s1[8]="ABCDEF78" Cast to unsigned char s2[4]={0xAB,0xCD,0xEF,0x78}
// unsigned char s1[8]="abcdef78" Cast to unsigned char s2[4]={0xab,0xcd,0xef,0x78}

// ASCII code value
// a - z : ( hex value ) 61 -- 7A
// A - Z : ( hex value ) 41 -- 5A
// 0 - 9 : { hex value } 30 -- 39
// { '0'- '9' } - '0' = { 0  -- 9  }
// { 'a - 'f' } - '0' = { 31 -- 36 }
// { 'A'- 'Z' } - '0' = { 11 -- 16 }

#include <iostream>

unsigned char* StrToHexArray( unsigned char* strSrc, unsigned char* strDest );

int main()
{
unsigned char s1[] = "12345678";
unsigned char s2[] = "ABCDEF78";
unsigned char s3[] = "abcdef78";

std::cout << s1 << " size is " << sizeof( s1 ) << std::endl;
std::cout << s2 << " size is " << sizeof( s2 ) << std::endl;
std::cout << s3 << " size is " << sizeof( s3 ) << std::endl;

unsigned char* s4 = new unsigned char[ 4 ];

StrToHexArray( s1, s4 );
for ( int i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;

StrToHexArray( s2, s4 );
for ( i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;

StrToHexArray( s3, s4 );
for ( i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;

delete s4;
return 0;
}

unsigned char* StrToHexArray( unsigned char* strSrc, unsigned char* strDest )
{
if ( strSrc == NULL || strDest == NULL )
return NULL;

int nDone = 0;
unsigned char* tmp = strSrc;
unsigned char* tmp2 = strDest;

while ( *strSrc )
{
nDone++;

unsigned char value = *strSrc - '0';

if ( value <= 9 )
NULL;
else if ( value >= 0x31 && value <= 0x36 )
value -= 0x27;
else if ( value >= 0x11 && value <= 0x16 )
value -= 0x07;

if ( ( nDone % 2 ) == 1 )
{
value <<= 4;
*strDest = value;
}

if ( ( nDone % 2 ) == 0 )
{
*strDest += value;
strDest++;
value = 0;
}
strSrc++;
}

strSrc = tmp;
strDest = tmp2;

return tmp;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值