Write a program that displays the binary representation of an integer as a \'1\'
ID: 3712851 • Letter: W
Question
Write a program that displays the binary representation of an integer as a '1' is shifted through all 32 bits of an integer storage location. Also print the: - Decimal value of the integer - The decimal value of each byte in the integer - The binary value of each byte in the integer Use the program from the examples, binary.c, as a starting point Ex: -- Integer: 1 Binary: 00000000000000000000000000000001 Bytes: 1 0 0 0 Binary: 00000001 00000000 00000000 00000000 Integer: 2 Binary: 00000000000000000000000000000010 Bytes: 2 0 0 0 Binary: 00000010 00000000 00000000 00000000 Integer: 4 Binary: 00000000000000000000000000000100 Bytes: 4 0 0 0 Binary: 00000100 00000000 00000000 00000000 . . . Integer: 2147483648 Binary: 10000000000000000000000000000000 Bytes: 0 0 0 128 Binary: 00000000 00000000 00000000 10000000
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int dec;
cout << "Enter the decimal to be converted: ";
cin >> dec;
int bin32[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int pos = 31; pos >= 0; --pos)
{
if (dec % 2)
bin32[pos] = 1;
dec /= 2;
}
cout << "The binary of the given number is: " << endl;
for (int p = 0; p <= 31; p++)
{
cout<<bin32[p];
}
cout << " The decimal value in each 8 bit is: " << endl;
int k=31 ,l=23,base=1,dec_value = 0;
for(int i=0;i<4;i++)
{
for(int j=k; j>l; --j)
{
dec_value =dec_value+ bin32[j]*base;
base = base*2;
}
base=0;
cout<<dec_value<<" ";
dec_value=0;
base=1;
k=k-8;
l=l-8;
}
}
Thanks;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.