-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex.h
More file actions
77 lines (63 loc) · 1.85 KB
/
hex.h
File metadata and controls
77 lines (63 loc) · 1.85 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#pragma once
#include <string>
#include <stdexcept>
class HexUtil
{
public:
static void hex_to_bytes(const std::string& input,unsigned char *& mem,uint32_t& size)
{
mem=NULL ;
if(input.length()&1 != 0)
throw std::runtime_error("String should have an even number of hex digits.") ;
size = (input.length()+1)/2 ;
mem = new unsigned char[size] ;
uint32_t n=0 ;
for(uint32_t i = 0; i < size; ++i)
{
mem[i] = 0 ;
for(int k=0;k<2;++k)
{
char b = input[n++] ;
if(b >= 'A' && b <= 'F')
mem[i] += (b-'A'+10) << 4*(1-k) ;
else if(b >= 'a' && b <= 'f')
mem[i] += (b-'a'+10) << 4*(1-k) ;
else if(b >= '0' && b <= '9')
mem[i] += (b-'0') << 4*(1-k) ;
else
throw std::runtime_error("supplied string is not purely hexadecimal") ;
}
}
}
static std::string bytes_to_string(const unsigned char *mem,uint32_t size,bool upper_case=false)
{
static const char outh[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' } ;
static const char outl[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' } ;
std::string res(size*2,' ') ;
for(uint32_t j = 0; j < size; j++)
if(upper_case)
{
res[2*j ] = outh[ (mem[j]>>4) ] ;
res[2*j+1] = outh[ mem[j] & 0xf ] ;
}
else
{
res[2*j ] = outl[ (mem[j]>>4) ] ;
res[2*j+1] = outl[ mem[j] & 0xf ] ;
}
return res ;
}
static void repeted_xor_encrypt(unsigned char *mem,uint32_t size,const unsigned char *key,uint32_t key_size)
{
for(int i=0;i<(int)size;++i)
mem[i] ^= key[i%key_size] ;
}
static uint32_t hamming_distance(const unsigned char *mem1,const unsigned char *mem2,uint32_t size)
{
uint32_t res = 0 ;
for(uint32_t i=0;i<size;++i)
for(int k=0;k<8;++k)
res += ( (mem1[i] & (1<<k)) != (mem2[i] & (1<<k)) ) ;
return res ;
}
};