-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathint_to_bytes.cpp
More file actions
53 lines (47 loc) · 1.48 KB
/
int_to_bytes.cpp
File metadata and controls
53 lines (47 loc) · 1.48 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
#include <cstdint>
#include <cstring>
#include <memory>
#include <ByteConvert/ByteConvert.hpp>
int main()
{
// Variable we will change into bytes
int val = 2;
// Array of bytes we expect to get back
uint8_t block[sizeof(int)];
memset(block,0,sizeof(int)-1);
block[sizeof(int)-1] = 2;
// Convert variable to bytes
size_t result_size = 0; // Size of block, we get back (you can pass nullptr if you know size of result)
uint8_t* result = ByteConvert::to_block(val, &result_size);
// Check result
if (result_size != sizeof(int)) {
// Error
delete[] result;
return -1;
}
for (size_t i = 0; i < result_size; i++) {
if (result[i] != block[i]) {
// Error: result and expected result don't match
delete[] result;
return -2;
}
}
// Clear result !!! It was allocated to heap so we need to manualy free it !!!!!!
delete[] result;
// Same as above, just implemented with smart pointers, which is safer
std::unique_ptr<uint8_t[]> result1(ByteConvert::to_block(val, &result_size));
// Check result
if (result_size != sizeof(int)) {
// Error
return -3;
}
for (size_t i = 0; i < result_size; i++) {
if (result1[i] != block[i]) {
// Error: result and expected result don't match
return -4;
}
}
// No need to free result1, because it clears itself when it goes out of scope
// Success
return 0;
}