#include 赞 踩 问题: Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。
字符串转换为16进制_字符串转16进制
将一个字符串转换为16进制数,例如“12”转换为0x12, "12345678"转换为0x12345678。
注意: 转换前每一个字符占用一个字节,转换后两个数字占用一个字节,如“12345678"占用8个字节,转换后占用四个字节:0x12, 0x34, 0x56, x078.
实现:#include <stdio.h>
#include <ctype.h>
int char2bcd(char str, unsigned char *value)
{
if(!str || !value){
return -1;
}
if(isdigit(str)){
*value = str - '0';
}else if(islower(str)){
*value = str - 'a' + 10;
}else if(isupper(str)){
*value = str- 'A' + 10;
}else{
return -1;
}
return 0;
}
int getValueFromStr(char *string, unsigned int length, unsigned char *value)
{
int i, ret;
unsigned char p,q;
if(!string || length < 0 || length>8){
return -1;
}
//*value = 0;
if(length%2){
ret = char2bcd(string[0], &p);
if(ret<0){
return -1;
}
value[0] = p;
for( i =1 ;i< ((length+1)>>1); i++){
ret = char2bcd(string[2*i - 1], &p);
if(ret < 0){
return -1;
}
ret = char2bcd(string[2*i], &q);
if(ret < 0){
return -1;
}
//*value = (*value << 8) + (p << 4) + q;
value[i] = (p << 4) + q;
}
}else{
for( i =0 ;i< (length>>1); i++){
ret = char2bcd(string[2*i], &p);
if(ret < 0){
return -1;
}
ret = char2bcd(string[2*i + 1], &q);
if(ret < 0){
return -1;
}
//*value = (*value << 8) + (p << 4) + q;
value[i] = (p << 4) + q;
}
}
return 0;
}