-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDigitConverter.h
More file actions
70 lines (59 loc) · 1.62 KB
/
DigitConverter.h
File metadata and controls
70 lines (59 loc) · 1.62 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
#pragma once
#ifndef DIGITCONVERTER_H
#define DIGITCONVERTER_H
#include <vector>
#include <stdlib.h>
#include <string>
#include "Strings.h"
#include "Utils.h"
using namespace std;
// Converts <see cref="IntX"/> digits to/from byte array.
class DigitConverter
{
public:
/*
/// <summary>
/// Converts big integer digits to bytes.
/// </summary>
/// <param name="digits"><see cref="IntX" /> digits.</param>
/// <returns>Resulting bytes.</returns>
/// <remarks>
/// Digits can be obtained using <see cref="IntX.GetInternalState" /> method.
/// </remarks>
*/
static vector<unsigned char> ToBytes(const vector<unsigned int> &digits)
{
if (digits.empty())
{
throw ArgumentNullException("digits");
} // end if
vector<unsigned char> bytes(digits.size() * 4);
memcpy(&bytes, &digits, bytes.size());
return bytes;
} // end function ToBytes
/*
/// <summary>
/// Converts bytes to big integer digits.
/// </summary>
/// <param name="bytes">Bytes.</param>
/// <returns>Resulting <see cref="IntX" /> digits.</returns>
/// <remarks>
/// Big integer can be created from digits using <see cref="IntX(uint[], bool)" /> constructor.
/// </remarks>
*/
static vector<unsigned int> FromBytes(const vector<unsigned char> &bytes)
{
if (bytes.empty())
{
throw ArgumentNullException("bytes");
} // end if
if (bytes.size() % 4 != 0)
{
throw ArgumentException(string(Strings::DigitBytesLengthInvalid) + "bytes");
} // end if
vector<unsigned int> digits(bytes.size() / 4);
memcpy(&digits, &bytes, bytes.size());
return digits;
} // end function FromBytes
}; // end class DigitConverter
#endif // !DIGITCONVERTER_H