-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex.cpp
More file actions
34 lines (31 loc) · 1.02 KB
/
hex.cpp
File metadata and controls
34 lines (31 loc) · 1.02 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
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//string to hex is pretty simple, take the ascii value of each char, take the lower nibble and the higher nibble,
string byteToHex(unsigned char byte) {
const char hexDigits[] = "0123456789abcdef";
string hex;
hex += hexDigits[(byte >> 4) & 15]; // High nibble
hex += hexDigits[byte & 15]; // Low nibble
return hex;
}
string step3Encode(const string& input) {
string hexString;
for (char c : input) {
hexString += byteToHex(static_cast<unsigned char>(c));
}
return hexString;
}
// Hex Decode
unsigned char hexToByte(const string& hex) {
return static_cast<unsigned char>(stoi(hex, nullptr, 16)); // Convert hex to byte
}
string step2decode(const string& hexString) {
string output;
for (size_t i = 0; i < hexString.length(); i += 2) {
string hexPair = hexString.substr(i, 2);
output += static_cast<char>(hexToByte(hexPair));
}
return output;
}