C++ - 十进制到二进制的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22746429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ - Decimal to binary converting
提问by user3478487
I wrote a 'simple' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there's a lot simpler way so can you show me? Here's the code:
我写了一个“简单”(我花了 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;
}
By the way it's complicated but I tried my best.
顺便说一下,这很复杂,但我尽力了。
edit - Here is the solution I ended up using:
编辑 - 这是我最终使用的解决方案:
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
回答by Brandon
std::bitset
has a .to_string()
method that returns a std::string
holding a text representation in binary, with leading-zero padding.
std::bitset
有一个.to_string()
方法,它返回一个std::string
以二进制形式保存的文本表示,前导零填充。
Choose the width of the bitset as needed for your data, e.g. std::bitset<32>
to get 32-character strings from 32-bit integers.
根据数据的需要选择位集的宽度,例如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;
}
EDIT:Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.
编辑:请不要编辑我对八进制和十六进制的回答。OP 特别要求十进制转二进制。
回答by Pathfinder
The following is a recursive function which takes a positive integer and prints its binary digits to the console.
下面是一个递归函数,它接受一个正整数并将其二进制数字打印到控制台。
Alex suggested, for efficiency, you may want to remove printf()
and store the result in memory... depending on storage method result may be reversed.
亚历克斯建议,为了效率,您可能希望删除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);
}
Credits to UoA ENGGEN 131
归功于 UoA ENGGEN 131
*Note: The benefit of using an unsigned int is that it can't be negative.
*注意:使用 unsigned int 的好处是它不能为负。
回答by skpro19
回答by piyushtechsavy
A pretty straight forward solution to print binary:
打印二进制文件的一个非常直接的解决方案:
#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];
}
}
回答by abe312
Non recursive solution:
非递归解决方案:
#include <iostream>
#include<string>
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
int main()
{
std::string i= toBinary(10);
std::cout<<i;
}
Recursive solution:
递归解决方案:
#include <iostream>
#include<string>
std::string r="";
std::string toBinary(int n)
{
r=(n%2==0 ?"0":"1")+r;
if (n / 2 != 0) {
toBinary(n / 2);
}
return r;
}
int main()
{
std::string i=toBinary(10);
std::cout<<i;
}
回答by Alex
An int
variable is not in decimal, it's in binary. What you're looking for is a binary string representation of the number, which you can get by applying a mask that filters individual bits, and then printing them:
一个int
变量是不是小数,它的二进制。您正在寻找的是数字的二进制字符串表示形式,您可以通过应用过滤单个位的掩码然后打印它们来获得它:
for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
cout << value & (1 << i) ? '1' : '0';
That's the solution if your question is algorithmic. If not, you should use the std::bitsetclass to handle this for you:
如果您的问题是算法问题,那就是解决方案。如果没有,您应该使用std::bitset类来为您处理:
bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
回答by Vlad from Moscow
Here are two approaches. The one is similar to your approach
这里有两种方法。一个类似于你的方法
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
const unsigned long long base = 2;
std::string s;
s.reserve( std::numeric_limits<unsigned long long>::digits );
do { s.push_back( x % base + '0' ); } while ( x /= base );
std::cout << std::string( s.rbegin(), s.rend() ) << std::endl;
}
}
and the other uses std::bitset as others suggested.
另一个使用 std::bitset 就像其他人建议的那样。
#include <iostream>
#include <string>
#include <bitset>
#include <limits>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
std::string s =
std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();
std::string::size_type n = s.find( '1' );
std::cout << s.substr( n ) << std::endl;
}
}
回答by Jan Christoph Uhde
Here is modern variant that can be used for ints
of different sizes.
这是可用于ints
不同尺寸的现代变体。
#include <type_traits>
#include <bitset>
template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
return std::bitset<sizeof(T) * 8>(i).to_string();
}
回答by Kiril Ilarionov
The conversion from natural number to a binary string:
自然数到二进制字符串的转换:
string toBinary(int n) {
if (n==0) return "0";
else if (n==1) return "1";
else if (n%2 == 0) return toBinary(n/2) + "0";
else if (n%2 != 0) return toBinary(n/2) + "1";
}
回答by Omid
Your solution needs a modification. The final string should be reversed before returning:
您的解决方案需要修改。最后的字符串应该在返回之前反转:
std::reverse(r.begin(), r.end());
return r;