-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBit.java
More file actions
75 lines (68 loc) · 1.64 KB
/
Bit.java
File metadata and controls
75 lines (68 loc) · 1.64 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
71
72
73
74
75
/**
* class thart represent 1 bit of number
*/
public class Bit{
/**
* Value tha represented by a 1bit String
*/
protected String value;
/**
* Class constructor
* @param bilangan biner sebagai data
*/
public Bit(String value){
this.value=value;
}
/**
* Class constructor
* @param value decimal value as the data
* @param bitLength the length of the bit
*/
public Bit(int value,int bitLength){
this.value=this.toBinary(value,bitLength);
}
/**
* Getter for the value
* @return string berupa bilangan biner
*/
public String getValue(){
return this.value;
}
/**
* Setter for the value attributes
* @param value bilangan biner baru
*/
public void setValue(String value){
this.value=value;
}
/**
* Method to change the decimal number to binary number
* @return the decimal number of the given binary number
*/
public int toDecimal(){
int res=0;
for(int i=this.value.length()-1;i>=0;i--){
if(this.value.charAt(i)=='1'){
res+=Math.pow(2,this.value.length()-1-i);
}
}
return res;
}
/**
* Method to change the decimal number to binary number
* @param val decimal number that will be changed top binary number
* @param bitLength the length of binary number
* @return String value that represent the binary number of the decimal that has been provided by the user
*/
public String toBinary(int val,int bitLength){
String str="";
while(val>0&&str.length()<bitLength){
str=(val%2)+str;
val/=2;
}
while(str.length()<bitLength){
str='0'+str;
}
return str;
}
}