Please complete task 2 and 3 in c++ binary (base 2) numbers into their hexadecim
ID: 3829507 • Letter: P
Question
Please complete task 2 and 3 in c++
binary (base 2) numbers into their hexadecimal equivalents. Your program should ask the user to input a positive integer between 0 and 255 Your program should then display, in a tabular fashion, the given number, and it's binary and hexadecimal equivalents. Task 1. (10 points) Using the provided code ("dec2bin arr.cpp" and dec2 bin s cpp"), write a function to convert any integer number between 0 and 255 to their binary equivalent. Please include the leading zeroes for the binary numbers. Task 2. (80 points0 Write a function that would convert an 8-bit binary number into it's hexadecimal equivalent. Note: if you find this option easier, it is ok to implement two functions, one for binary-to-decimal conversion, and one for decimal-to-hexadecimal conversion Sample run: Please enter a number between 0 and 255: 33 Decimal Hexadecimal Binary 00100001 33 0x 21Explanation / Answer
Function to convert binary to hexadecimal is:
void reverseStr(string &str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i=0; i<n/2; i++)
swap(str[i], str[n-i-1]);
}
void BinaryToHex(long int binary)
{int counter=0;
int sum=0;
b=num;
while(b!=0)
{
sum+=(b%10)*(pow(2,counter));
b/=10;
counter++;
}
cout<<sum<<" ";
string hex="";
while(sum!=0)
{
int c=sum%16;
if(c>=10)
{
switch(c)
{
case 10:hex+="A";
break;
case 11:hex+="B";
break;
case 12:hex+="C";
break;
case 13:hex+="D";
break;
case 14:hex+="E";
break;
case 15:hex+="F";
}
}
else
{
hex+=(char)c+48;
}
sum/=16;
}
reverseStr(hex);
cout<<hex;
}
Converting roman to decimal:
int convert(char c)
{
if (c == 'I')
return 1;
if (c == 'V')
return 5;
if (c == 'X')
return 10;
if (c == 'L')
return 50;
if (c == 'C')
return 100;
if (c == 'D')
return 500;
if (c == 'M')
return 1000;
return -1;
}
int RomanToDecimal(string &roman)
{
int Decimal = 0;
for (int i=0; i<roman.length(); i++)
{
// Get value of s[i]
int s1 = convert(roman[i]);
if (i+1 < roman.length())
{
// Get value of s[i+1]
int s2 = convert(roman[i+1]);
if (s1 >= s2)
{
Decimal = Decimal + s1;
}
else
{
Decimal = Decimal + s2 - s1;
i++;
}
}
else
{
Decimal = Decimal + s1;
i++;
}
}
return Decimal;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.