简体   繁体   English

C中的十进制到八进制

[英]Decimal to octal in C

I have just begun teaching myself C out of KN King's C Programming: A Modern Approach (2ndEdn). 我刚开始用KN King's C Programming:A Modern Approach(2ndEdn)教自己C语言。

I'm enjoying it, but am hoping to post the odd question here for advice if appropriate because unfortunately I don't have a tutor and some bits raise more questions then they answer! 我很享受,但是如果合适的话,我希望在这里发出奇怪的问题以获得建议,因为不幸的是我没有导师,有些人提出了更多问题然后他们回答了!

I'm doing a question on taking an integer entered and displaying it in octal. 我正在做一个关于输入整数并以八进制显示它的问题。 It says there is an easy way to do it, but that comes later in the book. 它说有一种简单的方法可以做到,但这本书后面会有。 I have come up with the following: 我想出了以下内容:

// Convert a number to octal

int n, n2, n3, n4, n5, n6;

printf("Enter a number between 0 and 32767: ");

scanf("%d", &n);

n6 = n % 8;
n5 = (n / 8) % 8;
n4 = ((n / 8) / 8) % 8;
n3 = (((n / 8) / 8) / 8) % 8;
n2 = ((((n / 8) / 8) / 8) / 8) % 8;

printf("%d%d%d%d%d", n2, n3, n4, n5, n6);

It works OK, but I'm not good at math and was wondering if there is a more efficient way of doing this or have I done it the only way possible... 它运作正常,但我不擅长数学,并且想知道是否有更有效的方法来做到这一点,或者我是否尽可能地完成了它...

If anyone else has the book it's Q4 p.71. 如果其他人有这本书,那就是Q4 p.71。

Thanks for your time. 谢谢你的时间。 Andrew 安德鲁

PS I did look in the search engine but couldn't find anything that was doing it this 'slower' way! PS我确实在搜索引擎中查找了但是找不到任何以“慢”方式执行的操作!

Everyone is right in saying that there's a built-in way to do that with printf . 每个人都说得对,有一种内置的方法可以用printf做到这一点。 But what about doing it yourself? 但是自己做呢?

The first thing that came to mind is that one octal digit is exactly three bits. 首先想到的是一个八进制数字正好是三位。 Therefore you can do the conversion this way: 因此,您可以通过这种方式进行转换:

  • Loop while n != 0 循环while n != 0
  • Isolate the leftmost 3 bits of n into d and print d n的最左边3位隔离成d并打印d
  • Shift n 3 bits to the left n 3比特向左

The code is trivial, but I 'm not providing it so you can do it yourself (you will need to be familiar with the bitwise and shift operators in order to do it). 代码很简单,但我没有提供它,所以你可以自己做(你需要熟悉按位移位 运算符才能这样做)。

The easy way is probably to use printf() 's %o format specifier : 简单的方法可能是使用printf()%o 格式说明符

scanf("%d", &n);
printf("%o", n);

Others have posted the real, production code answer, and now I see from your comments that you haven't done loops yet. 其他人发布了真实的生产代码答案,现在我从你的评论中看到你还没有完成循环。 Perhaps your book is trying to teach you about recursion: 也许你的书试图教你递归:

void print_oct(int n)
{
    if (n != 0) {
        print_oct(n / 8);
        printf("%d", n % 8);
    }
}

This works for n > 0. 这适用于n> 0。

/* Converts a positive base_10 into base_b */
int DecimalToBase(int n, int b)
{
    int rslt=0, digitPos=1;
    while (n)
    {
        rslt += (n%b)*digitPos;
        n /= b;
        digitPos *= 10;
    }
    return rslt;
}

With loops you can roll up your five very similar lines like this: 使用循环,您可以像这样卷起五条非常相似的线:

for (int d = 8 * 8 * 8 * 8; d > 0; d /= 8)
    printf("%d", n / d % 8);
printf("\n");

d will start at 8 * 8 * 8 * 8 , which is the divisor you use for n2 and then step through 8 * 8 * 8 , 8 * 8 , 8 and finally 1 , which is the divisor for n6 , printing each digit along the way. d将开始在8 * 8 * 8 * 8这是您使用的除数n2 ,然后通过步骤8 * 8 * 88 * 8 8 ,最后1 ,这对于除数n6 ,沿着打印每个数字方式。

A good compiler will actually optimize this by unrolling it back into five lines, so you'll get almost the same thing you started with. 一个好的编译器实际上会通过将它展开回五行来优化它,所以你将得到几乎与你开始时相同的东西。 The advantage of writing it as a loop is that you can't make a mistake in just one of the lines. 将其作为循环编写的优点是,您不能只在其中一行中出错。

The compiler will also take care of replacing divisions by 8 with shifts by 3 bits. 编译器还将使用3位移位替换8。 Both give the same result in binary, but the latter is faster. 两者都以二进制形式给出相同的结果,但后者更快。

Since only basics are introduced you don't want (at least at this point) to use functions, loops, bitwise operators, %o format specifier and all that stuff. 由于只引入了基础知识,所以你不希望(至少在这一点上)使用函数,循环,按位运算符, %o格式说明符和所有这些东西。 Here is my basic solution: 这是我的基本解决方案:

int n, d1, d2, d3, d4, d5, o;

printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);

d5 = n % 8;
n /= 8;
d4 = n % 8;
n /= 8;
d3 = n % 8;
n /= 8;
d2 = n % 8;
n /= 8;
d1 = n % 8;

o = 10000 * d1 + 1000 * d2 + 100 * d3 + 10 * d4 + d5;

printf("In octal, your number is: %.5d\n", o);

Note that since n is not needed in output, you can modify (divide) it for every step (thus saving divides, which are computationally and relatively expensive). 请注意,由于输出中不需要n ,因此可以为每个步骤修改(除)(因此可以节省分数,这在计算上相对昂贵)。 You are safe up to 32767 (in octal: 77777 ), as 32768 (8*8*8*8*8 = 8^5 = (2^3)^5 = 2^15) is the first number, that requires six digits in octal: 100000 . 你是安全的32767 (在八进制: 77777 ),因为32768 (8 * 8 * 8 * 8 * 8 = 8 ^ 5 =(2 ^ 3)^ 5 = 2 ^ 15)是第一个数字,需要六个八进制数字: 100000

This o variable is not really needed, morever it will not work when int is signed 16-bit (on some ancient system), so from this point it's better to just print separate digits. 这个o变量并不是真正需要的,当int被16位签名时(在一些古老的系统上),它不会起作用,因此从这一点开始,最好只打印单独的数字。

Existing answers aren't clean enough for my liking. 根据自己的喜好,现有答案不够干净。 Here's mine: 这是我的:

#include <stdio.h>

#define OCTALBASE    8
#define OCTALSIZE    8

int main(int argc, char **argv) {
  int indecimal = 1337;
  char output[OCTALSIZE + 1];
  output[OCTALSIZE] = '\0';

  int outindex = OCTALSIZE;
  int outdigit = 0;
  int outvalue = indecimal;
  while (--outindex >= 0) {
    outdigit = outvalue % OCTALBASE;
    if (outvalue > 0 || outdigit > 0)
      { output[outindex] = '0' + outdigit; }
    else { output[outindex] = ' '; }
    outvalue /= OCTALBASE;
  }

  fprintf(stdout, "{ DEC: %8d, OCT: %s }\n", indecimal, output);
  fflush(stdout);

  return 0;
}

Result: 结果:

{ DEC:     1337, OCT:     2471 }

Convert Decimal to Octal in C Language C语言将十进制转换为八进制

#include<stdio.h>
#include<conio.h>
void main()
{
    A:
    long int n,n1,m=1,rem,ans=0;
    clrscr();
    printf("\nEnter Your Decimal No :: ");
    scanf("%ld",&n);

    n1=n;
    while(n>0)
    {
        rem=n%8;
        ans=(rem*m)+ans;
        n=n/8;
        m=m*10;
    }

    printf("\nYour Decimal No is :: %ld",n1);
    printf("\nConvert into Octal No is :: %ld",ans);

    printf("\n\nPress 0 to Continue...");
    if(getch()=='0')
        goto A;
    printf("\n\n\n\tThank You");
    getch();
}

Use %o format specifier inside printf printf使用%o格式说明符

printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);
printf("%o", n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM