C语言 C语言中十进制转二进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14280336/
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
Convert decimal to binary in C
提问by mrpopo
I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn't work:
我正在尝试将十进制转换为二进制,例如 192 到 11000000。我只需要一些简单的代码来执行此操作,但到目前为止我拥有的代码不起作用:
void dectobin(int value, char* output)
{
int i;
output[5] = '#include <stdio.h>
#include <string.h>
int main()
{
long decimal, tempDecimal;
char binary[65];
int index = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal value : ");
scanf("%ld", &decimal);
/* Copies decimal value to temp variable */
tempDecimal = decimal;
while(tempDecimal!=0)
{
/* Finds decimal%2 and adds to the binary value */
binary[index] = (tempDecimal % 2) + '0';
tempDecimal /= 2;
index++;
}
binary[index] = '/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '#include <stdio.h>
#include <stdlib.h>
void bin(int num) {
int n = num;
char *s = malloc(sizeof(int) * 8);
int i, c = 0;
printf("%d\n", num);
for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
n = num >> i;
*(s + c) = (n & 1) ? '1' : '0';
c++;
}
*(s + c) = NULL;
printf("%s", s); // or you can also return the string s and then free it whenever needed
}
int main(int argc, char *argv[]) {
bin(atoi(argv[1]));
return EXIT_SUCCESS;
}
'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '#include <stdio.h>
int main()
{
long long int a,c;
int i=0,count=0;
char bol[10000];
scanf("%lld", &a);
c = a;
while(a!=0)
{
bol[i] = a%2;
a = a / 2;
count++;
i++;
}
if(c==0)
{
printf("0");
}
else
{
for(i=count-1; i>=0; i--)
{
printf("%d", bol[i]);
}
}
printf("\n");
return 0;
}
';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
';
/* Reverse the binary value found */
strrev(binary);
printf("\nDecimal value = %ld\n", decimal);
printf("Binary value of decimal = %s", binary);
return 0;
}
';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Any help would be much appreciated!
任何帮助将非常感激!
回答by Agent_L
The value is not decimal. All values in computer's memory are binary.
该值不是十进制的。计算机内存中的所有值都是二进制的。
What you are trying to do is to convert int to a string using specific base.
There's a function for that, it's called itoa.
http://www.cplusplus.com/reference/cstdlib/itoa/
您要做的是使用特定基数将 int 转换为字符串。有一个函数,它被称为itoa。
http://www.cplusplus.com/reference/cstdlib/itoa/
回答by Pankaj Prakash
First of all 192cannot be represented in 4bits
首先192不能用4位表示
192 = 1100 0000which required minimum 8bits.
192 = 1100 0000这需要最少的8位。
Here is a simple C program to convert Decimal number system to Binary number system
这是一个将十进制数系统转换为二进制数系统的简单C 程序
number=215
a=str(int(number//128>=1))+str(int(number%128>=64))+
str(int(((number%128)%64)>=32))+str(int((((number%12
8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
+str(int(((((((number%128)%64)%32)%16)%8)>=4)))
+str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
+str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
print(a)
回答by CubeSchrauber
5 digits are not enough for your example (192). Probably you should increase output
对于您的示例(192)来说,5 位数字是不够的。可能你应该增加output
回答by creaktive
A few days ago, I was searching for fast and portableway of doing sprintf("%d", num). Found this implementation at the page itoa with GCC:
几天前,我正在寻找快速且便携的方法sprintf("%d", num)。在带有 GCC 的 itoa页面上找到了这个实现:
#include <stdio.h>
void main()
{
int n,i,j,sum=0;
printf("Enter a Decimal number to convert it to binary : ");
scanf("%d",&n);
for(i=n,j=1;i>=1;j*=10,i/=2)
sum+=(i%2)*j;
printf("\n%d",sum);
}
回答by Arun Kumar
Here is the Algorithm to convert Decimal to Binary number
这是将十进制数转换为二进制数的算法
- Divide the input decimal number by 2 and store the remainder.
- Store the quotient back to the input number variable.
- Repeat this process till quotient becomes zero.
- Equivalent binary number will be the remainders in above process in reverse order.
- 将输入的十进制数除以 2 并存储余数。
- 将商存储回输入数字变量。
- 重复这个过程直到商变为零。
- 等价的二进制数将逆序为上述过程中的余数。
You can check c program here http://www.techcrashcourse.com/2015/08/c-program-to-convert-decimal-number-binary.html
你可以在这里查看 c 程序http://www.techcrashcourse.com/2015/08/c-program-to-convert-decimal-number-binary.html
回答by Pratik
So iteration 1 of your loop:
value = 192
i = 4
output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 2 of your loop:
value = 96
i = 3
output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 3 of your loop:
value = 48
i = 2
output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 4 of your loop:
value = 24
i = 1
output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 5 of your loop:
value = 12
i = 0
output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
Final string: "00000" and you wanted: "11000000"
回答by Roy
You can do it using while loop under a function also. I was just searching the solve for mine but the solves i get were not suitable, so I have done it accordingly the practical approach (divide using 2 until getting 0 and store the reminder in an array) and print the reverse of the array and Shared Here
您也可以在函数下使用 while 循环来完成。我只是在寻找我的解决方案,但我得到的解决方案不合适,所以我按照实际方法做了相应的处理(使用 2 进行划分,直到得到 0 并将提醒存储在数组中)并打印数组的反向并共享这里
output[8] = 'loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned
';
for (i = 7; i >= 0; --i, value >>= 1)
回答by Adedamola Opalade
You can also use the 'if', 'else', statements to write this code.
您还可以使用“if”、“else”语句来编写此代码。
回答by Kalpa D. Fernando
This is the simplest way to do it
这是最简单的方法
##代码##回答by Mike
So... did you check the output of your code to understand why it doesn't work?
那么...您是否检查了代码的输出以了解它为什么不起作用?
##代码##See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
看到你的代码有什么问题吗?不。我也没有,你只是走得不够远。将您的输出/循环更改为:
##代码##And then you'll have the correct result returned.
然后你会得到正确的结果。
I would recomend just a more general approach, you're using a fixed length string, which limits you to binary numbers of a certian length. You might want to do something like:
我只推荐一种更通用的方法,您使用的是固定长度的字符串,它将您限制为特定长度的二进制数。您可能想要执行以下操作:
##代码##
