Program to Invert a hexadecimal number in C [duplicate] - c

This question already exists:
Invert hexadecimal number: C Program [closed]
Closed 2 years ago.
My Approach:
Step 1. Firstly I converted Hexadecimal number into decimal number. (Hexa to decimal logic)
Then I Invert decimal number's bits using ~ operator and unsigned char datatype variable.
Step 2. And then I convert that decimal number into Hexadecimal number. (decimal to hexa logic)
Hence i got inverted hexadecimal number.
Input and output are string of hexadecimal numbers.
#include <stdio.h>
#include<string.h>
#include<math.h>
int
main ()
{
long decimal, qu, rem;
int k, j = 0;
char hexa[100];
int p = 0;
int dig, temp;
unsigned char re = 0;
char hex[32] = "42"; //input
int len = strlen (hex);
len--;
for (int i = len; i >= 0; i--)
{
switch (hex[i])
{
case 'A':
dig = 10;
break;
case 'B':
dig = 11;
break;
case 'C':
dig = 12;
break;
case 'D':
dig = 13;
break;
case 'E':
dig = 14;
break;
case 'F':
dig = 15;
break;
default:
dig = hex[i] - 48;
break;
}
temp = temp + dig * pow (16, p);
p++;
re = temp;
re = ~re;
}
qu = re;
while (qu != 0)
{
rem = qu % 16;
if (rem < 10)
hexa[j++] = 48 + rem;
else
hexa[j++] = 55 + rem;
qu = qu / 16;
}
for (k = j; k >= 0; k--)
{
printf ("%c", hexa[k]);
}
return 0;
}

#include <stdlib.h>
#include <stdio.h>
int main() {
printf("Please enter some hex: ");
unsigned int hex;
// scan input as hex into an integer
scanf("%x", &hex);
// truncate the last byte into a char
unsigned char c = hex;
// invert it
c = ~c;
// print it back out as uppercase hex
printf("Inverted hex: %02X\n", c);
return 0;
}

Well this maybe enough. This essential doing the same steps what you described, but with less code.
#include <stdio.h>
#include <string.h>
int main()
{
char * hex = "42ABE3";
unsigned dec;
for(int i = 0; i < strlen(hex); i++) {
sscanf(hex + i, "%1X", &dec);
printf("%X", 15 - dec);
}
}
Output
BD541C
Note that this code did not check if sscanf was successfull, but you could add that if you need.

Related

Converting Hexadecimal string to int

Write a C function, that accepts a null-terminated string, containing a hexadecimal string, and returns the integer value. You cannot call any C library function, except strlen() to code the function. The decimal string will only contain 0-4 ASCII characters from ‘0’ through ‘9’ and ‘A’ through ‘F’. No error handling is required. If the string is empty, then return a value of 0.
I've constantly tried fixing my errors, but once I fix them, new errors pop up, resulting in me being confused.
#include <stdlib.h> /*used for EXIT_SUCCESS */
#include <stdio.h> /*used for printf */
#include <string.h> /* used for strlen */
#include <stdbool.h> /* used for bool */
#include <math.h>
unsigned int hexStringTouint(const char str[], int length, int n[])
{
int i, j;
int intvalue = 0;
int digit;
for(i = (length-1), j = 0; i --, j++)
{
if(n[i]>='0' && n[i] <='9')
{
digit = n[i] - 0x30;
}
else if(n[i]>= 'A' && n[i] <= 'F')
{
switch(n[i])
{
case 'A': digit = 10; break;
case 'B': digit = 11; break;
case 'C': digit = 12; break;
case 'D': digit = 13; break;
case 'E': digit = 14; break;
case 'F': digit = 15; break;
}
}
intvalue += digit*pow(16,j);
}
printf("int value is %d\n", intvalue);
return 0;
}
int main(void)
{
int i, length, intvalue;
unsigned char n[] = "";
printf("Enter your hexadecimal string: ");
scanf("%c\n", n);
intvalue = 0;
length = strlen(n);
return EXIT_SUCCESS;
}
I am getting error messages saying
expected ';' in 'for' statement specifier
and how const char* converts between pointers and integers.
Much of OP's code is the right track, yet various coding errors exist.
Add test condition
// for(i = (length-1), j = 0; i --, j++)
// v
for(i = (length-1), j = 0; i >= 0; i --, j++)
cannot call any C library function, except strlen()
// intvalue += digit*pow(16,j);
intvalue += digit*(1u << (4*j));
Return the value
Requirement "... and returns the integer value"
//int intvalue = 0;
//...
//printf("int value is %d\n", intvalue);
//return 0;
unsigned intvalue = 0;
...
printf("integer value is %u\n", intvalue);
return intvalue;
Buffer too small
// unsigned char n[] = "";
// scanf("%c\n", n);
char n[100] = "";
scanf("%99s", n);
hexStringTouint()
Function not called in main().
Other issues exist
A simpler approach
unsigned hexStringTouint2(const char *str) {
unsigned value = 0;
while (*str) {
unsigned digit = hexCharTouint(*str); // tbd code
value = value*16 + digit;
str++;
}
return value;
}

How to cast a string to a integer

I have a 40 digit hex number stored in a string, I have to store it inside a struct called Int40 that only contains a pointer to an int.
typedef struct Int40
{
// a dynamically allocated array to hold a 40
// digit integer, stored in reverse order
int *digits;
} Int40;
this is what I have tried
Int40 *parseString(char *str)
{
Int40 *value = malloc(sizeof(Int40) * MAX40);
for (int i = 0; i < MAX40; i++)
{
value[i] = (int)str[i];
}
return value;
}
int main()
{
Int40 *p;
p = parseString("0123456789abcdef0123456789abcdef01234567");
printf("-> %d\n", *p);
}
I know that an Int cant contain 40 digits thats why I tried to store each number from the string in an array of integers but my code doesnt seem to work.
Edit: Also the number contains letters because is a hex number, will I have to the get the ascii value of the hex number to be able to store it in the array of int, how do i do that?
You might do something like the following (note that I omit verification of the argument char* and also assume that hex characters are lowercase)
// with if statements:
Int40 *parseString(char *str)
{
Int40 *value = malloc(sizeof(Int40) * MAX40);
// save the digits array locally (same memory address as value)
int* digits = value->digits;
for (int i = 0; i < MAX40; i++)
{
char c = str[i];
// decimal digits case
if (c >= '0' && c <= '9') {
digits[i] = c - '0'; // subtract '0' to get the numberical value of c
} else { // hex case
digits[i] = (c - 'a') + 10; // subtract 'a' to get the numerical value of c as 0 + 10 for hex characters A - F
}
}
return value;
}
An alternative:
// with a switch statements:
Int40 *parseString(char *str)
{
Int40 *value = malloc(sizeof(Int40) * MAX40);
// save the digits array locally (same memory address as value)
int* digits = value->digits;
for (int i = 0; i < MAX40; i++)
{
char c = str[i];
switch (c) {
// hex 10 - 15
case 'a': case 'b': case 'c':
case 'd': case 'e': case 'f':
digits[i] = (c - 'a') + 10;
break;
// hex 0 - 9
default:
digits[i] = c - '0';
}
}
return value;
}
#include <stdio.h>
#include <stdlib.h>
typedef int* hex;
hex parseString(char *str)
{
hex value = (hex)malloc(sizeof(int)*40);
for (int i = 0; i < 40; i++)
{
value[i] = str[i];
}
return value;
}
int main()
{
hex p;
p = parseString("0123456789abcdef0123456789abcdef01234567");
printf("-> %d\n", p[0]);
}
...
#include <stdio.h>
#include <stdlib.h>
typedef struct Int40
{
int* hex;
}Int40;
Int40 parseString(char *str)
{
Int40 value;
value.hex = (int*)malloc(sizeof(int)*40);
for (int i = 0; i < 40; i++)
{
value.hex[i] = str[i];
}
return value;
}
int main()
{
Int40 p;
p = parseString("0123456789abcdef0123456789abcdef01234567");
printf("-> %d\n", p.hex[0]);
}

Binary fractional to hexadecimal error (turbo c)

I just revised this code to accept binary numbers with fractional part. Here's the code:
#include <stdio.h>
int main()
{
double binaryval, frac, z;
long int hexadecimalval = 0, i = 1, remainder, num, p;
clrscr();
printf("Enter the binary number: ");
scanf("%lf", &binaryval);
num = binaryval;
frac = binaryval - num;
while (binaryval != 0)
{
remainder = num % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Equivalent hexadecimal value: %lX", hexadecimalval);
printf(".");
while (binaryval != 0)
{
while(frac != 0)
{
z = frac * 2;
p = z;
frac = z - p;
}
remainder = p % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("%lX", hexadecimalval);
getch();
return 0;
}
so the problem is... it gives a totally wrong answer
SAMPLE OUTPUT:
Enter the binary number: 1111.1111
Equivalent hexadecimal value: FFFFFFFF.FFFFFFFF
And then I tried changing 'binaryval' into 'num' in this loop...
while (num != 0)
{
remainder = num % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = num / 10;
}
but it only lets the user input a binary number and nothing else. Also, I can't even return to my codes. It's kinda got "stuck" and I have to close my Turbo C to run it again.
Can someone please tell me what's the problem and the things that needed to be changed? Thanks in advance!
Here is a solution for you, it doesn't store very much internally as I examine the input by each character. The integral part is simple, just build the value. The fractional part is a bit more difficult, to align it correctly I have taken input 4 bits at a time.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
long whole=0;
int ch, fract=0, bits=0;
// integral part is straight fowrard
while ((ch=getchar()) != EOF && ch != '.' && ch != '\n') {
switch(ch) {
case '0':
whole = whole * 2;
break;
case '1':
whole = whole * 2 + 1;
break;
default:
printf("Bad input\n");
return 1;
}
}
printf("%lX", whole);
// fractional part is more tricky to align correctly
if (ch == '.') {
printf(".");
while ((ch=getchar()) != EOF && ch != '\n') {
switch(ch) {
case '0':
fract = fract * 2;
bits++;
break;
case '1':
fract = fract * 2 + 1;
bits++;
break;
default:
printf("Bad input\n");
return 1;
}
if (bits == 4) { // process 4 bits at a time
printf("%X", fract);
fract = 0;
bits = 0;
}
}
if(bits) { // deal with 1 to 3 trailing bits
printf("%X\n", fract << (4-bits));
}
}
printf("\n");
return 0;
}
Your sample input and another:
1111.1111
F.F
1.000001
1.04
For one thing, you need to change binaryval to num in your loops.

how to check if the input is a number or not in C?

In the main function of C:
void main(int argc, char **argv)
{
// do something here
}
In the command line, we will type any number for example 1 or 2 as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typed hello or c?
Another way of doing it is by using isdigit function. Below is the code for it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
printf ("Given input is a number\n");
}
You can use a function like strtol() which will convert a character array to a long.
It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.
See the following program for an example:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[]) {
int i;
long val;
char *next;
// Process each argument given.
for (i = 1; i < argc; i++) {
// Get value with failure detection.
val = strtol (argv[i], &next, 10);
// Check for empty string and characters left after conversion.
if ((next == argv[i]) || (*next != '\0')) {
printf ("'%s' is not valid\n", argv[i]);
} else {
printf ("'%s' gives %ld\n", argv[i], val);
}
}
return 0;
}
Running this, you can see it in operation:
pax> testprog hello "" 42 12.2 77x
'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
Using scanf is very easy, this is an example :
if (scanf("%d", &val_a_tester) == 1) {
... // it's an integer
}
A self-made solution:
bool isNumeric(const char *str)
{
while(*str != '\0')
{
if(*str < '0' || *str > '9')
return false;
str++;
}
return true;
}
Note that this solution should not be used in production-code, because it has severe limitations. But I like it for understanding C-Strings and ASCII.
Using fairly simple code:
int i;
int value;
int n;
char ch;
/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
n = sscanf(argv[i], "%d%c", &value, &ch);
if (n != 1) {
/* sscanf didn't find a number to convert, so it wasn't a number */
}
else {
/* It was */
}
}
I was struggling with this for awhile, so I thought I'd just add my two cents:
1) Create a separate function to check if an fgets input consists entirely of numbers:
int integerCheck(){
char myInput[4];
fgets(myInput, sizeof(myInput), stdin);
int counter = 0;
int i;
for (i=0; myInput[i]!= '\0'; i++){
if (isalpha(myInput[i]) != 0){
counter++;
if(counter > 0){
printf("Input error: Please try again. \n ");
return main();
}
}
}
return atoi(myInput);
}
The above starts a loop through every unit of an fgets input until the ending NULL value. If it comes across a letter or an operator, it adds "1" to the int "counter" which is initially set to 0. Once the counter becomes greater than 0, the nested if statement instructs the loop to print an error message & then restart the program. When the loops completes, if int 'counter' is still the value of 0, it returns the initially inputted integer to be used in the main function ...
2) the main function would be:
int main(void){
unsigned int numberOne;
unsigned int numberTwo;
numberOne = integerCheck();
numberTwo = integerCheck();
return numberOne*numberTwo;
}
Assuming both integers are inputted correctly, the example provided will yield the result of int "numberOne" multiplied by int "numberTwo". The program will repeat for however long it takes to get two properly inputted integers.
if (sscanf(command_level[2], "%f%c", &check_f, &check_c)!=1)
{
is_num=false;
}
else
{
is_num=true;
}
if(sscanf(command_level[2],"%f",&check_f) != 1)
{
is_num=false;
}
how about this?
This works for me
#include <string.h>
int isNumber(char *n) {
int i = strlen(n);
int isnum = (i>0);
while (i-- && isnum) {
if (!(n[i] >= '0' && n[i] <= '9')) {
isnum = 0;
}
}
return isnum;
}
e.g.:
printf("%i\n", isNumber("12")); // 1
printf("%i\n", isNumber("033")); // 1
printf("%i\n", isNumber("0")); // 1
printf("%i\n", isNumber("")); // 0
printf("%i\n", isNumber("aaa")); // 0
printf("%i\n", isNumber("\n")); // 0
printf("%i\n", isNumber("a0\n")); // 0
The C library function int isdigit(int c) checks if the passed character is a decimal digit character.
#include <stdio.h>
#include <ctype.h>
int main () {
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) ) {
printf("var1 = |%c| is a digit\n", var1 );
} else {
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) ) {
printf("var2 = |%c| is a digit\n", var2 );
} else {
printf("var2 = |%c| is not a digit\n", var2 );
}
return(0);
}
the result is :
var1 = |h| is not a digit
var2 = |2| is a digit
The sscanf() solution is better in terms of code lines. My answer here is a user-build function that does almost the same as sscanf(). Stores the converted number in a pointer and returns a value called "val". If val comes out as zero, then the input is in unsupported format, hence conversion failed. Hence, use the pointer value only when val is non-zero.
It works only if the input is in base-10 form.
#include <stdio.h>
#include <string.h>
int CONVERT_3(double* Amt){
char number[100];
// Input the Data
printf("\nPlease enter the amount (integer only)...");
fgets(number,sizeof(number),stdin);
// Detection-Conversion begins
int iters = strlen(number)-2;
int val = 1;
int pos;
double Amount = 0;
*Amt = 0;
for(int i = 0 ; i <= iters ; i++ ){
switch(i){
case 0:
if(number[i]=='+'){break;}
if(number[i]=='-'){val = 2; break;}
if(number[i]=='.'){val = val + 10; pos = 0; break;}
if(number[i]=='0'){Amount = 0; break;}
if(number[i]=='1'){Amount = 1; break;}
if(number[i]=='2'){Amount = 2; break;}
if(number[i]=='3'){Amount = 3; break;}
if(number[i]=='4'){Amount = 4; break;}
if(number[i]=='5'){Amount = 5; break;}
if(number[i]=='6'){Amount = 6; break;}
if(number[i]=='7'){Amount = 7; break;}
if(number[i]=='8'){Amount = 8; break;}
if(number[i]=='9'){Amount = 9; break;}
default:
switch(number[i]){
case '.':
val = val + 10;
pos = i;
break;
case '0':
Amount = (Amount)*10;
break;
case '1':
Amount = (Amount)*10 + 1;
break;
case '2':
Amount = (Amount)*10 + 2;
break;
case '3':
Amount = (Amount)*10 + 3;
break;
case '4':
Amount = (Amount)*10 + 4;
break;
case '5':
Amount = (Amount)*10 + 5;
break;
case '6':
Amount = (Amount)*10 + 6;
break;
case '7':
Amount = (Amount)*10 + 7;
break;
case '8':
Amount = (Amount)*10 + 8;
break;
case '9':
Amount = (Amount)*10 + 9;
break;
default:
val = 0;
}
}
if( (!val) | (val>20) ){val = 0; break;}// val == 0
}
if(val==1){*Amt = Amount;}
if(val==2){*Amt = 0 - Amount;}
if(val==11){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = Amount/den;
}
if(val==12){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = 0 - (Amount/den);
}
return val;
}
int main(void) {
double AM = 0;
int c = CONVERT_3(&AM);
printf("\n\n%d %lf\n",c,AM);
return(0);
}

Convert decimal to binary in C

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:
void dectobin(int value, char* output)
{
int i;
output[5] = '\0';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Any help would be much appreciated!
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/
First of all 192cannot be represented in 4 bits
192 = 1100 0000 which required minimum 8 bits.
Here is a simple C program to convert Decimal number system to Binary number system
#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] = '\0';
/* Reverse the binary value found */
strrev(binary);
printf("\nDecimal value = %ld\n", decimal);
printf("Binary value of decimal = %s", binary);
return 0;
}
5 digits are not enough for your example (192). Probably you should increase output
A few days ago, I was searching for fast and portable way of doing sprintf("%d", num). Found this implementation at the page itoa with GCC:
/**
* 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 = '\0'; 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-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
It looks like this, but be careful, you have to reverse the resulting string :-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char output[256]="";
int main()
{
int x= 192;
int n;
n = x;
int r;
do {
r = n % 2;
if (r == 1)
strcat(output,"1");
else strcat(output,"0");
n = n / 2;
}
while (n > 0);
printf("%s\n",output);
}
So... did you check the output of your code to understand why it doesn't work?
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"
See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
output[8] = '\0';
for (i = 7; i >= 0; --i, value >>= 1)
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:
loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned
#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;
}
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
#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;
}
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
void main()
{
int num, total = 0,item;
print f( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
print f("%d",item);
}
}
Convert Decimal to Binary in C Language
#include<stdio.h>
void main()
{
long int n,n1,m=1,rem,ans=0;
printf("\nEnter Your Decimal No (between 0 to 1023) :: ");
scanf("%ld",&n);
n1=n;
while(n>0)
{
rem=n%2;
ans=(rem*m)+ans;
n=n/2;
m=m*10;
}
printf("\nYour Decimal No is :: %ld",n1);
printf("\nConvert into Binary No is :: %ld",ans);
}
This is the simplest way to do it
#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);
}
This is a simple program to convert a number from decimal to binary
#include <stdio.h>
#include <conio.h>
void decToBinary(int);
int main()
{
int number;
printf("Enter number to convert to binary: ");
scanf("%d", &number);
decToBinary(number);
return 0;
}
void decToBinary(int num)
{
if (num == 0)
{
return ;
}
decToBinary(num / 2);
printf("%d", num % 2);
}
Output of the Program:
Perhaps understanding the algorithm would allow you write or modify your own code to suit what you need. I do see that you don't have enough char array length to display your binary value for 192 though (You need 8 digits of binary, but your code only gives 5 binary digits)
Here's a page that clearly explains the algorithm.
I'm not a C/C++ programmer so here's my C# code contribution based on the algorithm example.
int I = 0;
int Q = 95;
string B = "";
while (Q != 0)
{
Debug.Print(I.ToString());
B += (Q%2);
Q = Q/2;
Debug.Print(Q.ToString());
I++;
}
Debug.Print(B);
All the Debug.Print is just to show the output.
//decimal to binary converter
long int dec2bin(unsigned int decimal_number){
if (decimal_number == 0)
return 0;
else
return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
}
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)
You can also use the 'if', 'else', statements to write this code.
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;//To
k = (k > 0) ? printf("1") : printf("0");
}
getch();
return 0;
}

Resources