-
Notifications
You must be signed in to change notification settings - Fork 8
/
BytesHelper.sol
52 lines (42 loc) · 1.58 KB
/
BytesHelper.sol
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
pragma solidity ^0.4.6;
library BytesHelper {
function toBytes32(string self, uint startIndex) returns (bytes32 b) {
uint l = 32;
bytes memory bs = toBytes(self, startIndex, l);
for (uint x = 0; x < l; x++) {
b = bytes32(uint(b) + uint(uint(bs[x]) * (2 ** (8 * (l - 1 - x)))));
}
}
function toBytes(string self, uint startIndex, uint length) internal returns (bytes) {
bytes memory str = bytes(self);
bytes memory bs = new bytes(length);
uint maxIndex = ((str.length - startIndex) < (length * 2) ? (str.length - startIndex) : startIndex + (length * 2));
for (uint i = startIndex; i < maxIndex; i++) {
uint ii = i - startIndex;
bs[ii / 2] = byte(uint8(bs[ii / 2]) + (uint8(toByte(str[i])) * uint8(16 ** (1 - (ii % 2)))));
}
return bs;
}
function toASCIIString(address self) internal returns (string) {
return toASCIIString(uint(self), 20);
}
function toASCIIString(uint self, uint length) internal returns (string) {
bytes memory s = new bytes(length * 2);
for (uint i = 0; i < length; i++) {
byte b = byte(uint8(uint(self) / (2**(8*(length - 1 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = toChar(hi);
s[2*i+1] = toChar(lo);
}
return string(s);
}
function toChar(byte b) returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
function toByte(byte char) returns (byte c) {
if (uint8(char) > 0x57) return byte(uint8(char) - 0x57);
else return byte(uint8(char) - 0x30);
}
}