C语言 十进制转二进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7911651/
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
Decimal to Binary
提问by darksky
I have a number that I would like to convert to binary (from decimal) in C.
我有一个数字,我想在 C 中转换为二进制(从十进制)。
I would like my binary to always be in 5 bits (the decimal will never exceed 31). I already have a function that does it manually by dividing but that is hard to pad it to 5 bits.
我希望我的二进制始终为 5 位(十进制永远不会超过 31)。我已经有一个通过除法手动完成的功能,但很难将其填充到 5 位。
Is there any easier way? Perhaps using bitwise shift?
有没有更简单的方法?也许使用按位移位?
I would also like the binary to be represented in a char *
我还希望将二进制文件表示为 char *
回答by Aaron Dufour
Here's an elegant solution:
这是一个优雅的解决方案:
void getBin(int num, char *str)
{
*(str+5) = 'int main()
{
char str[6];
getBin(10, str);
printf("%s\n", str);
return 0;
}
';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
Here, we start by making sure the string ends in a null character. Then, we create a mask with a single one in it (its the mask you would expect, shifted to the left once to account for the shift in the first run of the while conditional). Each time through the loop, the mask is shifted one place to the right, and then the corresponding character is set to either a '1' or a '0' (the !!ensure that we are adding either a 0 or a 1 to '0'). Finally, when the 1 in the mask is shifted out of the number, the while loop ends.
在这里,我们首先确保字符串以空字符结尾。然后,我们创建一个包含单个掩码的掩码(它是您期望的掩码,向左移动一次以解释 while 条件的第一次运行中的移动)。每次循环时,掩码都会向右移动一位,然后将相应的字符设置为“1”或“0”(!!确保我们将 0 或 1 添加到'0')。最后,当掩码中的 1 移出数字时,while 循环结束。
To test it, use the following:
要测试它,请使用以下命令:
char s[9];
itoa(10, s, 2);
printf("%s\n", s);
回答by Salvatore Previti
If you don't need leading zeroes, you can just use itoa(value, outputstring, base)
如果你不需要前导零,你可以使用 itoa(value, outputstring, base)
For example
例如
1010
will print out
会打印出来
void tobin5str(int value, char* output)
{
int i;
output[5] = '01010
';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
int main()
{
char s[6];
tobin5str(10, s);
printf("%s\n", s);
return 0;
}
Else you can just write a very simple function.
否则,您可以只编写一个非常简单的函数。
void tobinstr(int value, int bitsCount, char* output)
{
int i;
output[bitsCount] = 'unsigned int x = 30;
char bits[] = "00000";
bits[4] = (x & 1) + '0';
x >>= 1;
bits[3] = (x & 1) + '0';
x >>= 1;
bits[2] = (x & 1) + '0';
x >>= 1;
bits[1] = (x & 1) + '0';
x >>= 1;
bits[0] = x + '0';
';
for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
will print out
会打印出来
static const char *bitstrings[] = {
"00000", "00001", "00010", … "11111"
};
A more generic approach can be a function that ask you how much bits to convert.
更通用的方法可以是询问您要转换多少位的函数。
char *bits = malloc(6);
bits[0] = (i & (1<<4)) ? '1' : '0'; /* you can also just write out the bit values, but the */
bits[1] = (i & (1<<3)) ? '1' : '0'; /* compiler should be able to optimize a constant! */
?
bits[6] = 0; /* null-terminate string*/
Of course bitsCount must be a value from 1 to 32, and the buffer string must be allocated for at least bitsCount + 1 characters.
当然 bitsCount 必须是 1 到 32 之间的值,并且必须至少为 bitsCount + 1 个字符分配缓冲区字符串。
回答by Mysticial
One approach is this:
一种方法是这样的:
#include <stdio.h>
#include <math.h>
void main(){
int binary[8], number, i; //for 5 bits use binary[5]
do{
printf("input a number: ");
scanf("%d",&number);
fflush(stdin);
}while(number>256 || number <0); //for 5 bits... 31 use number>31 || number <0
for (i=0; i<=7; i++) // for 5 bits use i<=4
{
binary[i]=number%2;
number = number/2;
}
for (i=7; i >=0; i--) //for 5 bits use i=4
printf("%d", binary[i]);
number=0; // its allready 0.
for (i=0; i<=7; i++) //for 5 bits use i<=4
{
number=number+binary[i]*pow(2,i);
}
printf("\n%c",number);
}
Probably not the most elegant approach...
可能不是最优雅的方法......
回答by derobert
For 31 values, instead of doing malloc to allocate a string, followed by the bit manipulation to fill it, you may just want to use a lookup table.
对于 31 个值,您可能只想使用查找表,而不是执行 malloc 分配字符串,然后进行位操作来填充它。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
int n, t = 0;
char *bin, b[2] = "";
scanf("%d", &n);
bin = (char*)malloc(sizeof(char) + 2);
while (n != 0)
{
t = n >> 1;
t = t << 1;
t = n - t;
n = n >> 1;
itoa(t, b, 10);
bin = realloc((char*)bin, sizeof(char) + 1);
strcat(bin, b);
}
strrev(bin);
printf("\n%s\n", bin);
return 0 ;
}
Then your conversion is as simple as return bitstrings[i]. If you're doing this often, this will be faster (by avoiding malloc).
那么您的转换就像return bitstrings[i]. 如果你经常这样做,这会更快(通过避免 malloc)。
Otherwise, you don't really need any shifting (except to make writing your constants easier); you can just use bit-and:
否则,您实际上不需要任何转换(除了使编写常量更容易);你可以只使用位和:
#include<stdio.h>
int mask = 1;
void decToBi(int);
void decToBi(int n){
for(int j=15;j>=0;j--){
int result;
result = n & (mask<<j);
if(result)
printf("1");
else
printf("0");
}
}
int main(){
int n;
scanf("%d",&n);
decToBi(n);
printf("\n");
return 0;
}
There is a (maybe) micro-optimization you can do if you assume ASCII, by using addition. You can also use a loop here, but I needed two lines for the comment :-P. Performance-wise, neither will matter. All the time is spent in malloc.
如果您假设 ASCII,则可以通过使用加法进行(也许)微优化。您也可以在这里使用循环,但我需要两行注释:-P。在性能方面,两者都无关紧要。所有的时间都花在 malloc 上。
回答by Diamantatos Paraskevas
You can always divide and pad it to 5 bits (did this to pad in 8 bits because printing a character like A would be the number 65 )
您始终可以将其划分并填充为 5 位(这样做是为了填充 8 位,因为打印像 A 这样的字符将是数字 65 )
char* to_bitstring(uint32_t val, char buffer[], int size) {
buffer[--size] = 0;
while (size > 0) {
buffer[--size] = (val % 2 ? '1' : '0');
val = val >> 1;
}
return buffer; /* convenience */
}
回答by Rahul Raina
Here is C program to convert decimal to binary using bitwise operator with any decimal supported by system and holding only the required memory
这是使用按位运算符将十进制转换为二进制的 C 程序,系统支持任何十进制并仅保留所需的内存
char buffer[17];
printf("%s\n", to_bitstring(42, buffer, sizeof(buffer)));
回答by Shrikrishna Padalkar
0000000000101010
Hope this helps
希望这可以帮助
回答by Hugo
My take:
我的看法:
int main() {
int n,c,k;
printf("Enter_an_integer_in_decimal_number_system:_");
scanf("%d",&n);
printf("%d_in_binary_number_system_is:_", n);
for (c = n; c > 0; c = c/2) {
k = c%2;
k = (k>0)? printf("1"):printf("0");
}
getch();
return 0;
}
This will write SIZE characters to BUFFER:
这会将 SIZE 个字符写入 BUFFER:
#include "stdio.h"
#include "conio.h"
int main(void)
{
int i, d , n = 1;
int store[10];
printf("Please enter a number to be converted to binary:\n");
scanf("%d",&d);
for (i=0;i<8 ;i++ )
store[i] = 0;
i = 0;
do{
if(d & n ){
n <<= 1; //10
store[i] = 1;
i++;
}
else {
n <<= 1;
store[i] = 0;
i++;
}
}while(n <= d);
printf("\n");
for (i=7;i>=0 ;i-- ){
printf("%d",store[i]);
if(i == 4)
printf(" ");
}
printf("\n");
return 0;
}
And will print:
并将打印:
##代码##
