0% found this document useful (0 votes)
8 views8 pages

Binary and Hexadecimal Conversions

The document contains three Java tasks related to number base conversions. Task 1 converts binary and hexadecimal numbers to decimal, Task 2 converts decimal numbers to binary and hexadecimal, and Task 3 converts binary fractions to decimal. Each task includes user input and output statements for displaying the results of the conversions.

Uploaded by

eshalk745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Binary and Hexadecimal Conversions

The document contains three Java tasks related to number base conversions. Task 1 converts binary and hexadecimal numbers to decimal, Task 2 converts decimal numbers to binary and hexadecimal, and Task 3 converts binary fractions to decimal. Each task includes user input and output statements for displaying the results of the conversions.

Uploaded by

eshalk745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SP23-BCS-095

TASK 1
package task1;

import [Link].*;
public class Task1 {

public static void main(String[] args) {


Scanner sc= new Scanner([Link]);
int num=0;

[Link]("Enter Binary Number: ");


num=[Link]();
int count=0;

int bin=num;
while(bin>0)
{
count++;
bin=bin/10;
}
[Link](count);

int sum=0;
for(int i=0; i<count; i++)
{
int dig=num%10;
int mult=(int)(dig*([Link](2, i)));

sum=sum+mult;
num=num/10;

[Link]("Conversion TO DECIMAL IS: "+ sum);


/Conversion from base 16 to Decimal
[Link]("Enter a hexadecimal number: ");
String hexStr = [Link]();

int decimalValue = 0;
int length = [Link]();
if (![Link]("[0-9A-Fa-f]+")) {
[Link]("Invalid hexadecimal number. Please
enter valid characters (0-9, A-F).");
return;
}

for (int i = 0; i < length; i++) {


char currentChar = [Link](length - 1 - i);
int currentValue;

if (currentChar >= '0' && currentChar <= '9') {


currentValue = currentChar - '0';
} else {
currentValue = [Link](currentChar) -
'A' + 10;
}
decimalValue += currentValue * [Link](16, i);
}

[Link]("Hexadecimal conversion to decimal = "


+ decimalValue);
}
}

TASK 2
package labtsk2;

import [Link].*;
public class LabTsk2 {

public static void main(String[] args) {


// TODO code application logic here
Scanner sc=new Scanner([Link]);
[Link]("Enter a decimal number:");
int decimalNum=[Link]();

// Decimal to Binary Conversion


int n=1;
int binResult=0;
int num=decimalNum;
while(num>0){
int digit=(num%2)*n;
binResult+=digit;
num/=2;
n*=10;
}
[Link]("decimal conversion to binary = " + binResult);

// Decimal to HexaDecimal conversion


String hexResult = "";

if (decimalNum == 0) {
hexResult = "0";
} else {
while (decimalNum > 0) {
int remainder = decimalNum % 16;
char hexDigit;
if (remainder < 10) {
hexDigit = (char) (remainder + '0');
} else {
hexDigit = (char) (remainder - 10 + 'A');
}
hexResult += hexDigit;
decimalNum /= 16;
}
}

[Link]("Decimal conversion to hexadecimal = "


+ hexResult);
}
}

TASK 3
package labtsk3;

import [Link].*;
public class LabTsk3 {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a binary fraction (e.g., 101.101): ");
String binaryFraction = [Link]();
String[] parts = [Link]("\\.");
String integerPart = parts[0];
String fractionalPart = [Link] > 1 ? parts[1] : "0";

double decimalValue = 0.0;


for (int i = 0; i < [Link](); i++) {
char bit = [Link]([Link]() - 1 - i);
if (bit == '1') {
decimalValue += [Link](2, i);
}
}

for (int i = 0; i < [Link](); i++) {


char bit = [Link](i);
if (bit == '1') {
decimalValue += [Link](2, -(i + 1));
}
}

[Link]("Binary fraction " + binaryFraction + " in decimal


is: " + decimalValue);
}
}

Common questions

Powered by AI

Improvements for handling inputs and exceptions include using try-catch blocks to handle invalid inputs, such as non-integer inputs for decimal numbers or non-hexadecimal strings for hex inputs. Input validation could be enhanced using regex for binary numbers too. Additionally, detailed error messages and prompts for re-entry upon invalid input exceptions would help in enhancing user interaction and program robustness .

The while loop is advantageous for number conversion when the termination condition depends on a dynamic run-time value rather than a static limit. It allows continuation until the specific condition (e.g., num > 0) is met, which suits conversions where the number of iterations depends on the number's magnitude, as seen when binary or decimal numbers are converted iteratively in the given Java tasks .

If the regular expression for validating hexadecimal strings is not properly implemented, invalid characters may be accepted, leading to incorrect conversion results. This can cause the program to either crash during processing or produce an incorrect decimal equivalent. Edge cases, such as lower-case hexadecimal characters, would be mishandled without proper validation, resulting in errors or incorrect outputs .

To enhance readability, the binary to decimal conversion could use an enhanced for loop with a descriptive variable name for bits. Intermediate results might be broken into helper methods, each handling individual bit processing or summation. Introducing comments to explain key operations, aligning variable names with their purpose, and employing Java's inbuilt methods like Integer.parseInt with radix 2 could also improve maintainability .

The code validates a hexadecimal input by checking if the string matches the regular expression pattern '[0-9A-Fa-f]+'. This pattern ensures that the input consists only of valid hexadecimal characters (0-9 and A-F/a-f). If the input doesn't match this pattern, the program outputs an error message indicating that the number is invalid and prompts the user to enter valid characters .

The conversion from a decimal to a hexadecimal involves repeatedly dividing the decimal number by 16 and capturing the remainder, which corresponds to a hexadecimal digit. If the remainder is less than 10, it is converted to its character representation directly. If it is 10 or higher, it maps to its respective letter representation (A-F). This division and capture routine continues until the decimal number becomes 0, building the hexadecimal string from the last remainder to the first .

The conversion from a binary to a decimal number involves the following steps: First, the binary number's length is determined by counting the digits. Then for each digit, the binary digit is multiplied by 2 raised to the power of its position index from the right end (0-based index). Each of these products is added to a cumulative sum, which gives the overall decimal number. For example, the binary number is split into individual digits, each digit is processed by the formula dig*(2^i), where i is the position from the right, and thus ultimately converting it to a decimal .

The program splits the binary fraction into integer and fraction parts using the decimal point as the delimiter. The integer part is converted to decimal by processing bits from right to left, multiplying each bit by 2 raised to the power of its index. The fractional part is handled by multiplying each bit by 2 raised to the negation of its position index, starting from -1. Both parts are summed to provide the total decimal value of the binary fraction .

While converting from hexadecimal to decimal, the Java code differentiates characters by checking their ASCII values. Characters between '0' and '9' are converted to their integer values by subtracting the ASCII value of '0'. Characters between 'A' and 'F' are converted by subtracting the ASCII value of 'A', then adding 10 to map them correctly to decimal values from 10 to 15, ensuring all hex character ranges are accurately handled .

The conversion process involves dividing the decimal number by 2 repeatedly and capturing the remainder each time. The remainders, representing binary digits, are multiplied by powers of 10 to reflect their place value in the binary system. As the number is divided, the remainder (either 0 or 1) is multiplied by an increasing power of 10 and accumulated to form the binary result. This process continues until the decimal number is reduced to 0, resulting in the final binary number .

You might also like