MD5 32位和16位互相進行轉換
阿新 • • 發佈:2019-01-05
MD5 從32位和16位互相進行轉換
程式碼如下:
程式碼塊
程式碼塊語法遵循標準markdown程式碼,例如:
// 16進位制字元轉10進位制
inline int hexToDec(char c) {
int n;
if (c >= '0' && c <= '9') {
n = c - '0';
} else {
n = c - 'a' + 10;
}
return n;
}
// 一個char中有2個16進位制,轉為2個10進位制字元
inline void intDecToHex(unsigned char n, char* buf) {
int t = 0;
char c;
t = n & 0x0f;
if (t >=0 && t <= 9) {
c = t + '0';
} else {
c = t - 10 + 'a';
}
buf[1] = c;
n = n >> 4;
t = n & 0x0f;
if (t >=0 && t <= 9) {
c = t + '0';
} else {
c = t - 10 + 'a';
}
buf[0] = c;
}
// 壓縮md5 32為 轉為16位
void encode32To16(const char* ori_str, unsigned char* out) {
short index = 0;
unsigned char tm;
for (int i = 0; i < 32; ++index) {
tm = 0;
short n = hexToDec(ori_str[i++]);
tm |= n;
tm = tm << 4 ;
n = hexToDec(ori_str[i++]);
tm |= n;
out[index] = tm;
}
return;
}
// 16位壓縮md5轉為32位
void decode16To32(unsigned char* ori_str, char* out) {
short index = 0;
char buf[2] = {0};
unsigned char tm;
int index_ = 0;
for (int i = 0; i < 16; ++i) {
intDecToHex(ori_str[i], buf);
out[index++] = buf[0];
out[index++] = buf[1];
index_ ++;
}
return;
}