Effacer les filtres
Effacer les filtres

decimal to binary manually

2 vues (au cours des 30 derniers jours)
Faisal Al-Wazir
Faisal Al-Wazir le 7 Mar 2022
Design a program using a flowchart that prompts the user for a positive integer number smaller than 256 (i.e. [0..255]) and converts it into an 8-bit binary number. The bits are the remainders of the successive divisions of the input number by 2. The first division remainder is the least significant bit (i.e. the right most), and the last division remainder is the most significant bit (i.e. the left most bit). The result should be stored as a string and then printed.
The following is a sample run: Please enter a number between 0 and 255: 83
The binary equivalent of 83 is 01010011
  3 commentaires
Faisal Al-Wazir
Faisal Al-Wazir le 7 Mar 2022
i have it in c++
#include<iostream>
using namespace std;
main(){
int num,length,n;
cout<<"Please enter a number between 0 and 255: ";
cin>> num; // Taking input
n=num; //Copy of input number for operations so that input number is stored intact
if(num>255 || num<0){ // Validating range
cout<<"Number out of range";
exit(0);
}
string binary=""; // Initializing Null (empty) String
while(n>0){ // Process of converting decimal to binary
binary=to_string(n%2)+binary; // Concatenating Strings (each new bit in front of other bits)
n=n/2;
}
length=binary.length(); // If length of binary is less than 8 then convert add trailing zeros in front
if(length<8){
for(int i=length+1;i<=8;i++)
binary="0"+binary;
}
cout<<"The binary equivalent of "<<num<<" is "<<binary;
}
Jaya
Jaya le 8 Mar 2022
Modifié(e) : Jaya le 8 Mar 2022
I didn't run this code but doesn't it work, you mean?
Since you asked a question in this forum I assume you need help on the Matlab version of the code you presented. In that case, please can you try rewriting in Matlab and paste here? But if your final requirement is not a Matlab code but rather help on the technical part then you may consider posting this in some Stack exchange type forums. That would be better for your scenario.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 8 Mar 2022
n=n/2;
There is an important difference between that operation in C and MATLAB. When n is a positive integer datatype, then n/2 truncates in C. For example in C integer 5/2 truncates to 2. However in MATLAB, the operation rounds so 5/2 would have an intermediate value of 2.5 and that would round to 3.
The way to handle the situation in MATLAB is to convert the values to double, carry out the floating point operation, then floor() the results

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by