-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary.java
108 lines (88 loc) · 2.26 KB
/
Binary.java
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
/**
*
* @author Jose Torres Velasco
*
* This class allow work with binary strings and make type conversions.
*/
public class Binary {
/**
*Converts an Integer value to a String that contains the binary
*representation of introduced value.
*
* @param Integer to convert
* @return Binary string
*/
public static String integerToBitsString(int integer) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 32; i++) {
result.append(((integer >>> (32 - i - 1)) & 1));
}
return result.toString();
}
/**
*Converts an Byte value to a String that contains the binary
*representation of introduced value.
*
* @param Byte to convert
* @return Binary string
*/
public static String byteToBitsString(byte b) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 8; i++) {
result.append(((b >>> (8 - i - 1)) & 1));
}
return result.toString();
}
/**
*Converts a binary string to his integer value.
*
* @param Binary string to convert
* @return Integer value.
*/
public static int bitsStringToInteger(String bits) {
int result = 0;
if (bits.length() > 32) {
throw new RuntimeException(
"Number introduced can't be longer than 32 bits");
} else {
for (int i = 0; i < bits.length(); i++) {
result <<= 1;
if (bits.charAt(i) != '0' && bits.charAt(i) != '1') {
throw new RuntimeException(
"Input string only can content 0 or 1");
} else {
if (bits.charAt(i) == '1') {
result |= 1;
}
}
}
}
return result;
}
/**
*Converts a binary string to his byte value.
*
* @param Binary string to convert
* @return Integer value.
*/
public static byte bitsStringToByte(String bits) {
byte result = 0;
if (bits.length() > 8) {
throw new RuntimeException(
"Number introduced can't be longer than 8 bits");
} else {
for (int i = 0; i < bits.length(); i++) {
result <<= 1;
if (bits.charAt(i) != '0' && bits.charAt(i) != '1') {
throw new RuntimeException(
"Input string only can content 0 or 1");
} else {
if (bits.charAt(i) == '1') {
result |= 1;
}
}
}
}
return result;
}
}