forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryToDecimal.java
More file actions
59 lines (51 loc) · 1.89 KB
/
BinaryToDecimal.java
File metadata and controls
59 lines (51 loc) · 1.89 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
package com.thealgorithms.conversions;
/**
* This class converts a Binary number to a Decimal number
*/
final class BinaryToDecimal {
private static final int BINARY_BASE = 2;
private BinaryToDecimal() {
}
/**
* Converts a binary number to its decimal equivalent.
*
* @param binaryNumber The binary number to convert.
* @return The decimal equivalent of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
*/
public static long binaryToDecimal(long binaryNumber) {
long decimalValue = 0;
long power = 0;
while (binaryNumber != 0) {
long digit = binaryNumber % 10;
if (digit > 1) {
throw new IllegalArgumentException("Incorrect binary digit: " + digit);
}
decimalValue += (long) (digit * Math.pow(BINARY_BASE, power++));
binaryNumber /= 10;
}
return decimalValue;
}
/**
* Converts a binary String to its decimal equivalent using bitwise operators.
*
* @param binary The binary number to convert.
* @return The decimal equivalent of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
*/
public static long binaryStringToDecimal(String binary) {
boolean isNegative = binary.charAt(0) == '-';
if (isNegative) {
binary = binary.substring(1);
}
long decimalValue = 0;
for (char bit : binary.toCharArray()) {
if (bit != '0' && bit != '1') {
throw new IllegalArgumentException("Incorrect binary digit: " + bit);
}
// shift left by 1 (multiply by 2) and add bit value
decimalValue = (decimalValue << 1) | (bit - '0');
}
return isNegative ? -decimalValue : decimalValue;
}
}