#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef unsigned char BYTE;
//字节流转数字
long long BytesToValue(BYTE *value,int base)
{
if (value == NULL)
abort();
while (*value == ' ')
value++; //跳过空格
int sign = 0;
long long total = 0;
if (*value == '-')
{
sign = -1;
value++;
}
if (*value == '+')
value++;
while (!(*value == ' ' || *value == 0))
{
total = total * base + *value - '0';
value++;
}
if (sign == -1)
{
return -total;
}
return total;
}
//数字转字节流
int valueToBytes(int value, BYTE *dest,int base)
{
BYTE *p = dest;
BYTE t;
do
{ unsigned char m=value % base;
*dest++ =m<10?m+'0':m+'A'-10;
} while ((value = value / base) != 0);
printf("ok__");
int len = dest - p;
*dest = '\0';
dest--;
while (dest>p)
{
t = *p;
*p = *dest;
*dest = t;
p++;
dest--;
}
return len;
}
BYTE *copyHex(BYTE *hex, BYTE t)
{
t = t < 10 ? (t + '0') : (t + 'A' - 10);
*hex++ = t;
return hex;
}
//字节流转16进制字符串
int bytesToHex(BYTE *bin, int len, BYTE *hex)
{
int i = 0;
BYTE *p = hex;
for (i = 0; i < len; i++, bin++)
{
hex = copyHex(hex, *bin >> 4);
hex = copyHex(hex, *bin & 0x0F);
}
*hex = '\0';
return hex - p;
}
BYTE hexToC(BYTE *hex)
{
if (*hex <= 'z' && *hex >= 'a')
return *hex - 'a' + 10;
if (*hex >= 'A' && *hex <= 'Z')
return *hex - 'A' + 10;
if (*hex >= '0' && *hex <= '9')
return *hex - '0';
return 0;
}
//16进制转字节流
int hexToBytes(BYTE *hex, BYTE *bin)
{
BYTE high = 0;
int highFlag = -1;
BYTE *p = bin;
while (*hex != '\0')
{
if (highFlag == 0)
*bin++ = (high << 4) | hexToC(hex);
else
high = hexToC(hex);
highFlag = highFlag == -1 ? 0 : -1;
hex++;
}
return bin - p;
}
int main(int argv, char **argc)
{
char hex[20] = "12345678910";
char bin[10] = {0};
char hex_result[20] = {0};
int len = 0;
len = hexToBytes(hex, bin);
printf("bin:%s binLen:%d \n", bin, len);
len = bytesToHex(bin, len, hex_result);
printf("hex:%s hexLen:%d\n", hex_result, len);
printf("byteToValue src:%s intResult:%lld", hex, BytesToValue(hex, 10));
int value = 12;
char result[20] = {0};
int resLen = valueToBytes(value, result,10);
printf("valueToBytes src:%d intResult:%s", value, result);
return 0;
}