LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)

 Linh 05-20-2004 09:58 AM

How do I add two octal number ?

How do I add two octal number ?

1) The number 27 and 156 are both octal, how do I add the two to where the result will be octal and not decimal which is 183.

a = 27 + 156

2) What function do I use to convert a number to binary, octal, and hexadecimal.

3) The function below convert an octal to string, but what is the function that convert a number to octal ?
single_char = strtoul (three_oct_char, NULL, 8);

 Hko 05-20-2004 10:52 AM

Re: How do I add two octal number ?

Assuming you're talking about C code...

Quote:
 1) The number 27 and 156 are both octal, how do I add the two to where the result will be octal and not decimal which is 183. a = 27 + 156
By specifying them as octal numbers by prefixing the numbers with a zero ('0'). Like this:

a = 027 + 0156;

if you also want to print the result as an octal number use %o in the printf:

printf("%o\n", a);

Quote:
 2) What function do I use to convert a number to binary, octal, and hexadecimal.
To specify a integer constant inside the C-code, prefix with '0' for octal, '0x' or '0X' for hexadecimal, and binary is not possible (in C).

To convert an integer to a string as octal or hexadecimal:
Code:

```#include <stdio.h> #define LEN 10 int a; char str[LEN+1]; a = 123; snprintf(str, LEN, "%o", a);  /* str gets octal representation of a */ snprintf(str, LEN, "%X", a);  /* str gets hexadecimal representation of a */```
To get a string in binary is not possible directly (in C) as far as I know. But you can use this function:
Code:

```#define NUMBITS 16 /* make sure str can store at least NUMBITS+1 char's     for example:  char str[NUMBITS+1]; */ void strbinary(char *str, int x) {     int i;     for (i = 0; i < NUMBITS; ++i) str[NUMBITS-i-1]=x&1<<i?'1':'0';     str[NUMBITS] = '\0'; }```
To read an integer from a string representing a dec, hex, oct or bin number:
Code:

```#include <stdio.h> #include <stdlib.h> int main() {         int a;         /* The strings below all represent (decimal) 123. */         a = (int)strtol("123", NULL, 10);  /* str is decimal (base 10) */         printf("%d\n", a);         a = (int)strtol("1111011", NULL, 2);  /* str is binary (base 2) */         printf("%d\n", a);         a = (int)strtol("173", NULL, 8);  /* str is octal (base 8) */         printf("%d\n", a);         a = (int)strtol("7B", NULL, 16);  /* str is hexadeciaml (base 16) */         printf("%d\n", a);         return 0; }```
Quote:
 3) The function below convert an octal to string, but what is the function that convert a number to octal ? single_char = strtoul (three_oct_char, NULL, 8);
Do you mean: how to print a integer (or single char for that matter) as an octal number? or how to convert an integer to string as octal?
Use printf() or snprintf() for this. See above how.

 Linh 05-20-2004 11:33 AM