正式到二进制源代码 [英] Demical to Binary Source Code

查看:65
本文介绍了正式到二进制源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.. !!
我是一个非常新的程序员,刚开始学习C ...
我需要制作一个简单的程序,将十进制数转换为其相等的二进制
但我遇到了一些困难!

这是我的源代码:

Hello everyone..!!
I am a very very new programmer who just started learning C...
I need to make a simple program that converts a decimal number to its equal binary
but i''m facing some difficulties!

Here is my source code:

#include <stdio.h>
#include <stdlib.h>

int main()

{
int a, b, c;
printf("Type a decimal number: ");
scanf("%d", &a);
if (a<0)
{
printf("The data is incorrect. \n");
printf("Type an unsigned number to continue. \n");
scanf("%d", &a);
}
b=a%2;
a=a/2;
c=a%2;
a=a/2;

printf("The binary number you are looking for is %d%d", c,b);
system("pause");
}



这样,我只能转换很小的数字,只需要2位数字即可.但是我也想使此程序也可以用于更大的数字...
我必须添加100个变量吗?我觉得这很愚蠢.
必须有一种方法可以重复此过程,直到结果为0 ...
我必须告诉你,我对C知之甚少,所以请不要给我一个复杂的答案,因为我不会理解它...

在此先感谢您.. !!!



That way I can only convert very small numbers which need only 2 digits to be made... But I want to make this program work for bigger numbers as well...
Do I have to add 100 variables..?? I think that''s stupid..
There must be a way to make this procedure repeat till the result is 0...
I must tell you that I know too little about C, so plz don''t give me a complex answer, for I won''t understand it...

Thank you in advance..!!!

推荐答案

此处是可以从十进制转换为2到36之间任意基数的函数.

Here is a function which can convert from decimal to any base between 2 and 36.

#include <stdio.h>
#include <Windows.h>

//This function is the same as ConvertFromDecimal, only it is hard coded to look as much like your solution as possible. Hopefully you can see the similarities.
int ConvertToBinary(char *szBuffer, int a) {
	//Simple: Zero is the same in any base, so if the number is 0, return 0. 
	if (nDecimal == 0) {
		strcpy(szBuffer, "0");
		return 1;
	}
	char szAlphabet[] = "01";
	unsigned nChar = 0; //The number of characters in our string so far
	//This loop follows the basic structure of your code, only in a loop.
	do {
		szBuffer[nChar++] = szAlphabet[a % 2]; //Notice the similarity here?
		a /= 2; //Notice the similarity here too?
	} while (a != 0); //Instead of just doing the same thing twice, hard coded, we do it in a loop until our number reaches 0.
	//Now we have our string, but it is backwards, so reverse it
	for (int nReverse = 0; nReverse < nChar / 2; ++nReverse) {
		char tmp = szBuffer[nReverse];
		szBuffer[nReverse] = szBuffer[nChar - nReverse - 1];
		szBuffer[nChar - nReverse - 1] = tmp;
	}
	szBuffer[nChar] = 0;
	return nChar;
}

int ConvertFromDecimal(char *szBuffer, int nDecimal, int nBase) {
	//Simple: Zero is the same in any base, so if the number is 0, return 0. 
	if (nDecimal == 0) {
		strcpy(szBuffer, "0");
		return 1;
	}
	//This is the possible characters we can use.
	//The first character is for number 0, 2nd character is for the number 1, ...
	//0 -> 0, 1 -> 1, ... 10 -> A, 11 -> B, ... 35 -> Z
	//This allows us to simply index character 10, for example, and get the character 'A'
	char szAlphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	unsigned nChar = 0; //The number of characters in our string so far
	//This loop follows the basic structure of your code, only in a loop.
	do {
		//Add a character to the end of our string buffer. "nDecimal % nBase" is the same as your "a%2"
		szBuffer[nChar++] = szAlphabet[nDecimal % nBase];
		//And now divide by the base. this is the same as your "a=a/2"
		nDecimal /= nBase; // Calculate new value of decimal
	} while (nDecimal != 0); //Keep going until our number is 0. i.e. nothing left
	//Now we have our string, but it is backwards, so reverse it
	//This swaps the first and last character, then the 2nd and 2nd last character, and so on
	//to swap 2 values, we have to save 1 into a temporary variable, then set that value, then set the other one
	for (int nReverse = 0; nReverse < nChar / 2; ++nReverse) {
		//Save the character at the start
		char tmp = szBuffer[nReverse];
		//Set the character at the start to the character which is the same distance from the end
		szBuffer[nReverse] = szBuffer[nChar - nReverse - 1];
		//Now set the character at the end to the one we saved earlier
		szBuffer[nChar - nReverse - 1] = tmp;
	}
	szBuffer[nChar] = 0; //Terminate the string. strings in C++ end with the NULL terminator character, ASCII 0.
	return nChar; //Return the length of the string. It could be useful for something
}

int main() {
	char szBuffer[16]; //This must be big enough to hold the output +1 byte for the terminator
	//Now just run some tests to check it is working. Compared to windows calculator.
	int n = 1;
	ConvertFromDecimal(szBuffer, n, 2);
	printf("%d in binary is %s\n", n, szBuffer);
	n = 5;
	ConvertFromDecimal(szBuffer, n, 2);
	printf("%d in binary is %s\n", n, szBuffer);
	n = 1085;
	ConvertFromDecimal(szBuffer, n, 2);
	printf("%d in binary is %s\n", n, szBuffer);
	n = 1000;
	ConvertFromDecimal(szBuffer, n, 2);
	printf("%d in binary is %s\n", n, szBuffer);
	n = 65536;
	ConvertFromDecimal(szBuffer, n, 2);
	printf("%d in binary is %s\n", n, szBuffer);
	return 0;
}




这段代码几乎完成了您正在做的事情,只是它处于循环状态,因此可以在任何大小的数字上使用.另外,代替2的硬编码基数,它将基数作为参数.


添加了更多注释以更好地解释算法




This code does pretty much what you were doing, only it is in a loop so it works on any size number. Also, in stead of a hard coded base of 2, it takes the base in as a parameter.


Added more comments to better explain algorithm


如果您尝试将十进制数实际转换为二进制等效值:
If you are trying to actually convert a decimal number into it''s binary equivilent:
decimal 23 -> binary 10111

有一些使它变得更容易的事情:
1)循环
2)二进制AND运算
3)按位移位运算符.

首先要意识到的是,您不想以输入数字的最低位(即最低有效位)开头,而是希望将其打印在右侧.因此,从最左边开始.假设我们只处理8位数字(即十进制0到255,包括十进制),则您希望将最上面的位打印为"1"或"0".
这是二进制AND运算符(``&'')出现的地方.

There there are a couple of things which make it easier:
1) A loop
2) The Binary AND operation
3) The bitwise shift operators.

The first thing to realize is that you don''t want to start with the bottom bit of the entered number - that is the least significant bit, and you want to print that on the right hand side. So, start with the left most bit. Assuming we are only dealing with 8 bit numbers (i.e. decimal 0 to 255 inclusive) you want to print the top most bit as a "1" or a "0"
This is where the Binary AND operator (''&'') comes in.

if ((myNumber & 0x80) != 0)
   {
   printf("1");
   }
else
   {
   printf("0");
   }


接下来需要做的是将刚检查的钻头移开.那就是按位移位运算符(<<<"和>>"")派上用场的地方.


The next thing you need to do is move the bit you just checked out of the way. That is where the bitwise shift operators ("<<" and ">>") come in handy.

myNumber = myNumber << 1;

将整数向左移动一位-等于将其乘以2.
然后,您需要做的就是设置一个循环:

Moves the whole number one place to the left - the equivalent of multiplying it by two.
Then all you need to do is set up a loop:

for (i = 0; i < 8; i++)
   {
   ...
   }


这不是最有效的方法-有很多更好的方法-但这确实为您提供了基础知识.您所需要做的就是将钻头固定在一起,看看会发生什么!



非常感谢,我已经理解了这一点……
我要写什么才能设置循环?我尝试了几件事,但无论输入什么数字,程序都不会写错"0" ...
而且您能告诉我"myNumber& 0x80"是什么意思吗? :-("


对不起!我认为有些事情太多了...:laugh:

OK:循环:


This isn''t the most efficient way to do it - there are a lot of much better ones - but it does give you the basics. All you have to do is bolt the bits together, and see what happens!



"Thank you very much, I understood this one till a certain point...
What do I write in order to set the loop? I tried a couple of things and althouth I get no error the program writes "0", no matter what number I enter...
And also could you tell me what "myNumber & 0x80" means?Cause i can''t understant it..! :-("


Sorry! I assumed a few things too many... :laugh:

OK: the loop:

for (i = 0; i < 8; i++)
   {
   ...
   }

这将建立一个循环并运行它. for循环具有三部分,以;"字符分隔:
for(设置代码;在仍然为真的情况下继续;每次到达循环代码的末尾时都要执行)
因此,上面的代码将一个名为i的整数(必须在方法顶部声明)设置为零值

This sets up a loop, and runs it. A for loop has three parts, separated by '';'' characters:
for ( set up code ; continue while still true condition ; do every time you get to the end of the loop code )
So the code above sets an integer called i (which you have to declare at the top of your method) to the value zero

i = 0

,然后循环运行,每次都将一个添加到i:

And then runs around the loop adding one to i each time:

i++

i仍小于8

i < 8

因此,它在循环中总共进行了八次,对于您使用的八位数字中的每一位一次.试试吧!将代码粘贴到您的程序中,然后添加行

So, it goes round the loop a total of eight times, once for each bit in the eight bit number you are working with. Try it! Paste the code into your program, and add the line

printf("%d\n", i);

在花括号之间.

另外一点也不是太复杂:

in between the curly brackets.

The other bit isn''t too complex either:

myNumber & 0x80

myNumber是一个变量,其中包含您要转换为二进制数的数字. &"是二进制AND运算符,0x80是一种写数字的方法,该数字不以10为底:"0x"位告诉编译器其后是以16为底的数字(即十六进制).为什么我们使用十六进制而不是十进制或二进制?因为二进制变得非常长,非常快,并且很难将十进制转换为机器正在执行的操作.当数字变大并且您需要确切知道多少时,使用十六进制会容易得多. Wiki应该在数字基础上有一些不错的东西,但是目前您只接受以十六进制设置哪些位比十进制设置的位更容易". :laugh:

在这种情况下,0x80是十六进制等效值,十进制为128,二进制为10000000.它实际上是一个数字,只有八位中的最高位设置为一个.当您使用二进制AND运算时,它将两个数字组合在一起,分别查看每个位.如果两个数字都设置了相同的位(或等于1),则在输出中将其设置为1.在所有其他情况下,它都设置为0.
因此,如果数字中的第八位为零,则0x80与任何数字的二进制与将为零;如果为八,则为非零.

这有意义吗,或者它有很多需要理解的地方-使用图片更容易了!



我写了这个,尽管编译器说没有错误,但是只要输入数字,它就会停止工作...!:-(

#include
#include

int main()
{
int myNumber,i;
printf("Give number:");
scanf(%d",myNumber);
如果(myNumber& 0x80!= 0)
{
printf("1");
}
其他
{
printf("0");
}
myNumber = myNumber<< 1;
对于(i = 0; i< 8; i ++)
{
printf(%d \ n",i);
}
system("pause");
}

我确定我犯了错误,但我找不到它们...
您的回答确实非常非常有帮助!!! :-)


首先-缩进您的代码!可以一目了然地查看正在发生的事情:

myNumber is a variable, which holds the number you want to convert to binary. ''&'' is the Binary AND operator, and 0x80 is a way of writing numbers which are not in base ten: the "0x" bit tells the compiler that what follows is a number in base 16, or Hex. Why do we use hex instead of decimal or binary? Because binary gets very long, very quickly, and decimal is difficult to mentally convert to what the machine is doing. It''s a lot easier to work with hex when numbers get big and you need a sense for how big exactly. Wiki should have some good stuff on number bases, but for the moment just accept that it is easier to "see" which bits are set in hex than it is in decimal. :laugh:

In this case, 0x80 is the hex equivalent of 128 in decimal, or 10000000 in binary. What it actually is in a number with just the top bit out of the eight set to one. When you use the binary AND operation, it combines the two numbers together, looking at each bit individually. If the same bit is set (or equal to 1) in both numbers, then it is set to 1 in the output. In all other cases it is set to 0.
So a binary AND of 0x80 and any number will be zero if the eighth bit in the number is zero, and non-zero if it is one.

Does that make sense, or is it a bit much to understand - it''s a lot easier with pictures!



I wrote this and although the compiler says that there are no errors, as soon as I type a number it stops working...!:-(

#include
#include

int main()
{
int myNumber, i;
printf("Give number: ");
scanf("%d", myNumber);
if (myNumber & 0x80 != 0)
{
printf("1");
}
else
{
printf("0");
}
myNumber = myNumber << 1;
for (i = 0; i < 8; i++)
{
printf("%d\n", i);
}
system("pause");
}

I''m certain that I''ve made mistakes, but I can''t find them...
Your answer was really very very helpful!!! :-)


First off - indent your code! It makes it a lot easier to see at a glance what is going on:

int main()
{
    int myNumber, i;
    printf("Give number: ");
    scanf("%d", myNumber);
    if ((myNumber & 0x80) != 0)
    {
        printf("1");
    }
    else
    {
        printf("0");
    }
    myNumber = myNumber << 1;
    for (i = 0; i < 8; i++)
    {
        printf("%d\n", i);
    }
    system("pause");
}

要做的是询问一个数字,从用户那里读取它并崩溃. :D

为什么会崩溃?因为您正在尝试将数字读取到错误的位置.您需要给它提供myNumber的地址,而不是内容:

What that will do is ask for a number, read it from the user and crash. :D

Why will it crash? Because you are trying to read the number into the wrong place. You need to give it the address of myNumber rather than the content:

scanf("%d", myNumber);

成为

scanf("%d", &myNumber);

(不要太担心这意味着什么-您的课程很快就会对此进行解释)

然后,它将处理八位中的最高位,然后在每次循环时打印出循环计数.
尝试在循环内移动if-else stuff:

(Don''t worry too much about what that means - your course will explain it pretty soon)

Then, it will process the top bit of the eight, before printing out the loop count each time it goes round.
Try moving the if-else stuff inside the loop:

int main()
{
    int myNumber = 0, i;
    printf("Give number: ");
    scanf("%d", &myNumber);
    for (i = 0; i < 8; i++)
    {
        if ((myNumber & 0x80) != 0)
        {
            printf("1");
        }
        else
        {
            printf("0");
        }
        myNumber = myNumber << 1;
    }
    system("pause");
}

(明白我对缩进的意思吗?)

[edit]如果条件可以处理优先级规则,请添加方括号:o-OriginalGriff [/edit]
[edit]将右"更改为左".按位移位运算符<<向左移动,而不是向右移动:o-OriginalGriff [/edit]

(See what I mean about indenting?)

[edit]Added brackets to if condition to handle precedence rules :o - OriginalGriff[/edit]
[edit]Changed "Right" to "Left". Bitwise shift operator << moves to the Left, not the Right :o - OriginalGriff[/edit]


此基本任务是教您如何编写自己的"Format/printf"例程,该技巧将在其他分配中很方便,因为此解决方案中使用了一些基本的循环和/或递归.

回到我不得不这样做的时候(当时"C"不存在:),我们使用了递归而不是循环,因为您确定了从右到左的每个数字,但想从左到右打印.递归可以帮助您做到这一点.

This basic assignment is to teach you how to write your own "Format / printf" routines, a skill that will come in handy in other assignments as some basic looping and/or recursion are used in this solution.

Back when I had to do this ("C" didn''t exist then :) we used recursion instead of loops since you determine each digit from right to left but want to print it from left to right. Recursion helps you do that.

#include "stdafx.h"
#include "stdlib.h"

char *ToChar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void print_radix(char **b, int v, int r)
{
    int d = v % r;
    v = v / r;
    if (v != 0)
        print_radix(b, v, r);
    *(*b) = ToChar[d];
    *b += 1;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char buf[128];
    char *p;
    int n;

    n = 2;
    p = buf;
    print_radix(&p, n, 2);
    *p = '\0';
    printf("%d in binary is %s\n", n, buf);

    n = 8;
    p = buf;
    print_radix(&p, n, 2);
    *p = '\0';
    printf("%d in binary is %s\n", n, buf);

    n = 257;
    p = buf;
    print_radix(&p, n, 2);
    *p = '\0';
    printf("%d in binary is %s\n", n, buf);

    n = 65535;
    p = buf;
    print_radix(&p, n, 2);
    *p = '\0';
    printf("%d in binary is %s\n", n, buf);

    return 0;
}


这篇关于正式到二进制源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆