-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdec2hex.cc
More file actions
55 lines (48 loc) · 1.28 KB
/
dec2hex.cc
File metadata and controls
55 lines (48 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* Converts decimal string to hexadecimal string.
* e.g. 256 -> 100
* len specifies the length of decimal string(dec)
* length of the output buffer(hex) should be at least len bytes.
*/
void dec2hex(char* dec, char* hex, int len){
/* 1248 encoding -> hex */
char hexmap[] = {
'0', '8', '4', 'C', '2', 'A', '6', 'E',
'1', '9', '5', 'D', '3', 'B', '7', 'F'
};
int bits = 0, part = 0;
char* g = dec;
char* p = hex;
char* const z = dec + len;
for (int rlen = len; rlen;){
int carry = 0, remainder = 0;
for (char* s = g; s != z; ++s){
int d = *s - '0';
remainder = d & 0x01;
*s = (char)((d >> 1) + carry + '0');
carry = remainder ? 5 : 0;
}
if (*g == '0'){
++g;
--rlen;
}
part <<= 1;
part |= remainder;
++bits;
/* 4 bits per group */
if (!(bits & 3)){
*(p++) = hexmap[part];
part = 0;
}
}
if (bits & 3){
part <<= 4 - (bits & 3);
*(p++) = hexmap[part];
}
*p = 0;
/* Reverse output string */
for (char* left = hex, *right = p - 1; left < right; ++left, --right){
char t = *left;
*left = *right;
*right = t;
}
}