我写了一个 '简单' (花了我 30 分钟) 程序,将十进制数转换为二进制。我确信有很多更简单的方法,所以你能告诉我吗?这是代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
system("clear");
cout << "Enter a decimal number: ";
cin >> a1;
a2 = a1; //we need our number for later on so we save it in another variable
while (a1!=0) //dividing by two until we hit 0
{
remainder = a1%2; //getting a remainder - decimal number(1 or 0)
a1 = a1/2; //dividing our number by two
maxtab++; //+1 to max elements of the table
}
maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
a1 = a2; //we must do calculations one more time so we're gatting back our original number
table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)
while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
{
remainder = a1%2; //getting a remainder
a1 = a1/2; //dividing by 2
table[tab] = remainder; //adding 0 or 1 to an element
tab++; //tab (element count) increases by 1 so next remainder is saved in another element
}
tab--; //same as with maxtab--
cout << "Your binary number: ";
while (tab>=0) //until we get to the 0 (1st) element of the table
{
cout << table[tab] << " "; //write the value of an element (0 or 1)
tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
}
cout << endl;
return 0;
}
顺便说一句,这很复杂,但我尽力了。
编辑-这是我最终使用的解决方案:
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
std::bitset
有一个.to_string()
方法,该方法返回一个std::string
,其中包含二进制文本表示形式,并带有前导零填充。
根据数据需要选择 bitset 的宽度,例如std::bitset<32>
从 32 位整数中获取 32 个字符的字符串。
#include <iostream>
#include <bitset>
int main()
{
std::string binary = std::bitset<8>(128).to_string(); //to binary
std::cout<<binary<<"\n";
unsigned long decimal = std::bitset<8>(binary).to_ulong();
std::cout<<decimal<<"\n";
return 0;
}
编辑:请不要编辑我的答案为八进制和十六进制。
以下是一个递归函数,它接受一个正整数并将其二进制数字打印到控制台。
Alex 建议,为了提高效率,您可能希望删除printf()
并将结果存储在内存中...根据存储方法,结果可能会反转。
/**
* Takes a unsigned integer, converts it into binary and prints it to the console.
* @param n the number to convert and print
*/
void convertToBinary(unsigned int n)
{
if (n / 2 != 0) {
convertToBinary(n / 2);
}
printf("%d", n % 2);
}
贷记 UoA ENGGEN 131
* 注意:使用 unsigned int 的好处是它不能为负。
您可以使用 std::bitset 将数字转换为其二进制格式。
使用以下代码段:
std::string binary = std::bitset<8>(n).to_string();
我在 stackoverflow 本身上找到了这个。我正在附加link。
一个非常简单的解决方案来打印二进制:
#include <iostream>
using namespace std;
int main()
{
int num,arr[64];
cin>>num;
int i=0,r;
while(num!=0)
{
r = num%2;
arr[i++] = r;
num /= 2;
}
for(int j=i-1;j>=0;j--){
cout<<arr[j];
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(15条)