Created
May 5, 2021 13:21
-
-
Save BT-ICD/475415d504bd3cc2fb2be726061f28df to your computer and use it in GitHub Desktop.
Example: Conversion from binary to decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example: Conversion from binary to decimal | |
* Reference: https://www.rapidtables.com/convert/number/binary-to-decimal.html, https://byjus.com/maths/binary-to-decimal-conversion/ | |
* Sample Data: | |
* 11 - 3 | |
* 111 - 7 | |
* 101 - 5 | |
* 1111 - 15 | |
* 1001 - 9 | |
* | |
* Example | |
* Given binary number = (1101)2 | |
* Now, multiplying each digit from MSB to LSB with reducing the power of the base number 2. | |
* 1 × 2 raised to 3 + 1 × 2 raised to 2 + 0 × 2 raised to 1 + 1 × 2 raised to 0 | |
* = 8 + 4 + 0 + 1 | |
* = 13 | |
* | |
* Thus, the equivalent decimal number for the given binary number (1101)2 is (13)10 | |
**/ | |
public class BinaryToDecimalDemo { | |
public static void main(String[] args) { | |
int num=1101, rem, ans=0, cnt=0; | |
while(num>0){ | |
rem=num%10; | |
num=num/10; | |
if(rem==0) | |
ans = ans + (0* (int) Math.pow(2,cnt)); | |
else | |
ans = ans + (1* (int) Math.pow(2,cnt)); | |
cnt++; | |
} | |
System.out.println(ans); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public class BinaryToDecimalDemo {
public static void main(String[] args) {
int num=1101, rem, ans=0, cnt=0;
while(num>0){
rem=num%10;
num=num/10;
ans = ans + (rem* (int) Math.pow(2,cnt));
cnt++;
}
System.out.println(ans);
}
}