-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexutils.js
122 lines (100 loc) · 2.73 KB
/
hexutils.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"use strict";
import { Buffer } from 'buffer';
export function x(data) {
return new Bytes(data);
}
export function bytesFromString(string, encoding = 'utf8') {
let bytebuffer = [];
const buffer = Buffer.from(string, encoding);
for (let i = 0; i < buffer.length; i++) {
bytebuffer.push(buffer[i]);
}
const bytes = new Bytes([...bytebuffer]);
return bytes;
}
export function bytesFromNumber(number, bytes = 1) {
let byteArray = [];
for (let i = 0; i < bytes; i++) {
byteArray.push(0);
}
for (let i = 0; i < byteArray.length; i++) {
const byte = number & 0xff;
byteArray[i] = byte;
number = (number - byte) / 256 ;
}
return byteArray;
}
class Bytes {
constructor(data) {
this.bytes = null;
if (typeof data === 'string') {
this.bytes = this.constructor.fromHexString(data.toUpperCase());
} else if (typeof data === 'array') {
this.bytes = data;
} else if (typeof data === 'number') {
this.bytes = [ data ];
} else if (typeof data === 'object') {
this.bytes = Array.from(data);
} else {
console.log(typeof data);
this.bytes = [];
}
}
static fromHexString(string) {
let array = [];
for (let i = 0, len = string.length; i < len; i+=2) {
array.push(parseInt(string.substr(i,2),16));
}
return array;
}
getArraySplittedBy(splitter) {
let splitted = [[]];
let i = 0;
this.array.forEach(byte => {
if (splitted[i].length >= 1 && byte == splitter) {
i++;
splitted[i] = [];
}
splitted[i].push(byte)
});
return splitted;
}
get number() {
let value = 0;
for (let i = 0; i < this.bytes.length; i++) {
value *= 256;
if (this.bytes[i] < 0) {
value += 256 + this.bytes[i];
} else {
value += this.bytes[i];
}
}
return value;
}
get array() {
return this.bytes;
}
get bitArray() {
let bits = [];
this.bytes.forEach(byte => {
for (let i = 7; i >= 0; i--) {
let bit = byte & (1 << i) ? 1 : 0;
bits.push(bit);
}
});
return bits;
}
get buffer() {
return Buffer.from(this.bytes);
}
get string() {
return this.buffer.toString('hex').toUpperCase();
}
get convertedString() {
let bytes = '';
this.bytes.forEach(bytes => {
bytes += String.fromCharCode(bytes);
});
return bytes;
}
}