I'm converting a 4 bytes integer to binary, reversing the bits order, converting back to decimal and printing the integer. When I convert back to decimal somehow the number 49 get added to the correct number. Let my give you some examples:
decimal->binary -> reversed binary ->decimal(correct answer | my answer)
123->00000000000000000000000001111011->11011110000000000000000000000000->3724541952 | 3724542001
1->00000000000000000000000000000001->10000000000000000000000000000000->2147483648 | 2147483697
Everytime my answer - correct answer= 49 . Here is my code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
uint32_t f;
int a[32]={0};
int i;
int dec, j = 0;
printf("Enter a value :");
scanf ("%" SCNu32, &f);
for(i=0;f>0;i++)
{
a[i]=f%2;
f=f/2;
}
printf("\n Binary number(LSB) is=");
for(i=0;i<=31;i++)
printf("%d",a[i]);
printf("\n");
for(i=31;i>=0;i--)
{
dec = dec + (1u << i) * (a[j] - '0');
j++;
}
printf("The decimal representation:%u", dec);
return 0;
}
For converting back to decimal I used #Pras answer from here: Converting array of binary numbers to decimal
dec is not initialized.
- '0' is inappropriate because a[j] is a bit (0 or 1), not a character code ('0' or '1').
Either j is not needed (you can use 31-i) or it is not calculated correctly (should start at 31 and work down to 0 while i starts at 0 and works up to 31, or j can be calculated from i in each iteration).
With those errors corrected, the program produces the desired output. However, there are a number of other issues regarding the correct declaration of main and certain aspects of style, so here is a new version addressing some of them:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
// Declare main as "int main(void)" or "int main(int argc, char *argv[])".
int main(void)
{
uint32_t f;
int a[32] = { 0 };
/* Do not declare identifiers where you do not need them. This avoids
various errors that can occur where things are mistakenly used where
they were not intended.
i is used only in loops, so it is declared only inside those loops.
dec is only needed after some other work, so it is declared later.
j is not needed at all.
*/
printf("Enter a value:");
/* Do not put a space between a function and the parentheses for its
arguments.
*/
scanf("%" SCNu32, &f);
// Use more spaces; do not crowd symbols together.
for (int i=0; f>0; i++) // Or "for (int i = 0; i > 0; i++)".
/* Indent a loop body more than the code it is in; do not put { and }
further to the left and keep the loop body at the same indentation as
the code it is in.
*/
{
a[i] = f%2;
f = f/2;
}
printf("\nBinary number (LSB) is = ");
for (int i=0; i<=31; i++)
printf("%d", a[i]);
printf("\n");
/* Put blank lines in transitions between code that finishes one task,
like printing output, and code that starts another task, like
converting to binary.
*/
int dec = 0; // Declare dec here, just before it is needed.
for (int i=31; i>=0; i--)
{
/* Remove "- '0'" here. a[j] is a bit (0 or 1), not a character code
('0' or '1').
Do not use j. This loop has a counter, i. Using two counters for
different things may have confused you. While you want i to run
from 0 to 31, you want j to run from 31 to 0. You could use a
separate j for this, but it is easily replaced by 31-i.
*/
dec = dec + (1u << i) * a[31-i];
}
// Include spaces in output, like after the colon, to avoid crowding.
/* Print a "\n" at the end of each line of output. C is designed to use
"\n" to end lines, not to start them, because "\n" causes output to be
sent to interactive devices immediately instead of buffered.
*/
printf("The decimal representation: %u\n", dec);
return 0;
}
Related
I am very new to Coding. Here is a program that I wrote to convert decimal to binary
but there is one problem I am getting the result but it's in reverse
Example: Binary of 122 is 1111010 and I'm getting output 0101111.
Can anyone please tell me is it possible to reverse the output in my code?
Or what changes can I make in the following to get the correct output?
#include<stdio.h>
int main()
{
int n, q, r;
printf("Enter the decimal Number : ");
scanf("%d", &n);
int num=n;
while(n!=0)
{
r=n%2;
q=n/2;
printf("%d", r);
n=q;
}
return 0;
}
Seems like you are new to coding. It doesn't matter here is the problem.
Converting decimal to binary is like this,
eg:
division by 2
quotient
reminder
bit
10/2
5
0
0
5/2
2
1
1
2/2
1
0
2
1/2
0
1
3
=(1010)
So the output should have digits from bottom to top of the reminder column. Your output is printed from top to bottom.
See the code below where you need an array in order to store reminders and print the array in reverse order so you get the output you need
#include<stdio.h>
#include<stdlib.h>
int main(void){
int a[10],n,i;
printf("Enter the decimal Number : ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}
void display(unsigned n)
{
if(n == 0) return;
display(n /2);
printf("%d", n % 2);
}
and example usage:
https://godbolt.org/z/ahGPc74nf
As a homework: how to correctly handle 0?
Or not recursive version. This one can print or not leading zeroes:
void display(unsigned n, int printzeroes)
{
unsigned mask = 1 << (CHAR_BIT * sizeof(mask) - 1);
int print = printzeroes;
while(mask)
{
if(n & mask)
{
print = 1;
}
if(print) printf("%d", !!(n & mask));
mask >>= 1;
}
}
And usage: https://godbolt.org/z/7Eq71TMWb
First of all, please note that all numbers in a C program are to be regarded as binary. It's a common misconception among beginners that different number formats somehow co-exist in the executable program. But everything there is raw binary.
Sure the programmer may write numbers in different formats 7, 07 or 0x7 in the source code, but they get translated to binary by the compiler. Therefore, converting between binary and "x" doesn't make sense, because everything is already binary. You may however, convert from binary to a decimal string or similar, for the purpose of displaying a number to the user etc.
With that misconception out of the way - yes, you can create a binary string with the method you picked, dividing by ten and checking the remainder. The problem with that approach is that you'll get the most significant digit first. This is why you get the number backwards. So in order to do that, you'd have to store down the string in a character array first, before displaying it.
A more convenient way would be to use the "bitwise" operators like & and shift to mask out bit by bit in the data. Basically this:
if(n & (1u << bit)) // 1u to avoid shifting signed type
printf("1");
else
printf("0");
Where bit is the bit position 7,6,5... down to 0. If we prefer an up-counting loop instead, we can tweak the code into:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
...
}
And finally we can make the output a bit more compact, which is just a stylistic concern:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
printf("%c", n & mask ? '1' : '0');
}
If you aren't dead certain about C operator precedence, then use parenthesis, which is perfectly fine too:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << (8-i-1);
printf("%c", (n & mask) ? '1' : '0');
}
Here's the homework demanded by 0___________:
void printbin(int n)
{
static int depth;
if (n) ++depth, printbin(n / 2), --depth;
else if (depth) return; // print leading 0 only for n = 0
printf("%d", n % 2);
}
A leading 0 is not printed unless on the topmost recursion level.
You could maybe create an array of size 32 and keep adding the digits to the array. Or create a int variable and add the digits to the variable.
int result = 0;
while(n!=0)
{
r=n%2;
n=n/2;
result = result*10+r;
}
I am writing a program that converts a given bit string (up to 32-bits) into decimal assuming the input is given in unsigned magnitude and two's complement. I am reading each bit in from the user one char at a time and attempting to store it into an array, but the array doesn't have a required size. Is there a way to get the array to go through the loop without the array size being known? I also am trying to figure out a way to not use the pow and multiplication functions. I am posting my code below, if you have any ideas please
#include "stdio.h"
#include "math.h"
#define MAX_BITS 32
#define ENTER '\n'
#define NUMBER_TWO 2
int main()
{
int unsignedMag;
int twosComp;
int negation[n];
int bitStore[n];
char enter;
//Input from the User
printf("Enter up to 32 bits (hit 'enter' to terminate early): ");
//Reads the first bit as a character
char bit = getchar();
while (getchar != enter) {
bit = bit - '0';
scanf("%c", &bitStore[bit]);
getchar();
}
//Terminates if user hits enter
if (bit == enter) {
return 0;
}
//Continue through code
else {
//Loop to calculate unsigned magnitude
for (int i = 0; i < bitStore[i]; i++) {
unsignedMag = unsignedMag + (bitStore[i] * pow(NUMBER_TWO, i));
}
//Loop to calculate complete negation
for (int j = 0; j < bitStore; j++) {
negation[j] = ~bitStore[j]
}
negation = negation + 1;
for (int l = 0; l < negation; l++) {
twosComp = twosComp + (negation[l] * pow(NUMBER_TWO, l));
}
}
return 0;
}
"Is there a way to get the array to go through the loop without the array size being known?"
No. Array sizes are fixed at the point the array is declared and the size is knownable: e.g. #Observer
size_t size = sizeof bitStore/sizeof bitStore[0];
Instead, since code has "given bit string (up to 32-bits) ", define the array as size 32 (or 33 is a string is desired).
Keep track of how much of the array was assigned.
//int bitStore[n];
int bitStore[MAX_BITS];
int count = 0;
// char bit = getchar();
int bit = getchar(); // Use `int` to account for potentially 257 different values
//while (getchar != enter) {
while (count < MAX_BITS && (bit == '0' || bit == '1')) {
bit = bit - '0';
// Do not read again, instead save result.
//scanf("%c", &bitStore[bit]);
bitStore[count++] = bit;
// getchar();
bit = getchar();
}
to not use the pow and multiplication functions.
Simply add or multiply by 2 via a shift. It is unclear why OP has a goal of not using "multiplication". I see little reason to prohibit *. A good compiler will emit efficient code when the underlying multiplication is expensive as *2 is trivial to optimize.
// int unsignedMag;
unsigned unsignedMag = 0; // initialize
// for (int i = 0; i < bitStore[i]; i++) {
for (int i = 0; i < count; i++) {
// preferred code, yet OP wants to avoid * for unclear reasons
// unsignedMag = unsignedMag*2 + bitStore[i];
unsignedMag = unsignedMag + unsignedMag + bitStore[i];
}
pow() is good to avoid for many reasons here. Most of all, using double math for an integer problem runs into precision issues with wide integers.
converts a given bit string (up to 32-bits) into decimal
Note that a bitStore[] array is not needed for this task. Simply form unsignedMag as data is read.
I'm trying to generate a random 10-digit code, but even though I use the absolute value of every number in the code, it still sometimes prints a negative value
#include <stdio.h>
int main()
{
int i;
int r;
int barcode[11];
srand(time(NULL));
for(i=0;i <= 10;i++){
r = rand() % 10;
barcode[i] = abs(r);
}
printf("%d",barcode);
return 0;
}
Because you are actually printing the address of an integer array, not a string.
This line:
printf("%d",barcode);
Basically prints the address of barcode as a signed integer instead of the contents of barcode.
You of course could do this:
printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);
But perhaps a better way is to generate a string of characters instead of an array of integers. Quick mod to your code is to add to '0' to each random value in each interation of the loop and append to a char array.
int main()
{
int i;
int r;
char barcode[11]; // array of chars instead of ints
srand(time(NULL));
for(i=0; i < 10; i++) // loop 10 times, not 11
{
r = rand() % 10;
barcode[i] = '0' + r; // convert the value of r to a printable char
}
barcode[10] = '\0'; // null terminate your string
printf("%s\n",barcode);
return 0;
}
The above will generate a 10 digit code, with a small possibility of the first number being a leading zero. If that's not what you want, that's a simple bug fix. (Which I'll leave up to you...)
I am writing a C program to get Fibonacci number, the user needs to put the first 2 numbers and the sequence starts from there. Here is my code:
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int i, input[MAX_SIZE];
printf("please Enter first 2 digit of the Sequence\n");
scanf("%d, %d" , &input[0], &input[1]);
for (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
return 0;
}
But when i run the code with a input 2 and 3, I get a output like this 1499141456, which is clearly not the sequence. please help.
When you exit from the loop i is equal to MAX_SIZE
printf("%d\n", input[i]);
you are printing a value outside of the bounds of the array (input[MAX_SIZE]).
It's because the result in your code is bigger that the maximum value an int can handle
Live example here!
From Wikipedia
The number 2,147,483,647 (or hexadecimal 7FFF,FFFF16) is the maximum
positive value for a 32-bit signed binary integer in computing. It is
therefore the maximum value for variables declared as integers (e.g.,
as int) in many programming languages, and the maximum possible score,
money, etc. for many video games.
Here's where it goes wrong
[...]
433494437 + 701408733 = 1134903170
701408733 + 1134903170 = 1836311903
1134903170 + 1836311903 = -1323752223
put print statement inside for loop braces.
or (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
As a follow up to my last question here.
I was trying out the reverse of the previous question. That is, converting an input of the form A1 to output of the form R1C1 (for more, look at my last question).
I'll explain my algorithm. Let us suppose we need to convert BC23 to R23C55. I extracted 'BC' and '23' from BC23 and stored them in seperate arrays. I made another array which stores values 1,2,3...so on for A,B,C respectively as and when they come in input. For example my array would contain 2 and 3 as first two elements respectively for B and C. Then I used some mathematics to convert it into a number, in this case 55 for BC.
Here is the complete code.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char str[5],col[5],row[5];
int i=0,j=0,k=0,lenOfstr,lenOfcol;
scanf("%s",str);
while(str[i]>='A'&&str[i]<='Z')
{
col[j]=str[i];
i++;
j++;
}
col[j]='\0';
lenOfstr=strlen(str);
lenOfcol=strlen(col);
int ascCol[lenOfcol];
for(i=lenOfcol;i<lenOfstr;i++)
{
row[k]=str[i];
k++;
}
row[k]='\0';
for(i=0;i<lenOfcol;i++)
{
ascCol[i]=col[i]-64;
}
int sum=0;
for(i=0;i<lenOfcol;i++)
{
sum=sum+(ascCol[i]*pow(26,lenOfcol-i-1));
}
printf("%d",sum);
return 0;
}
There is a slight bug in the last strip of code which I am not able to debug.
int sum=0;
for(i=0;i<lenOfcol;i++)
{
sum=sum+(ascCol[i]*pow(26,lenOfcol-i-1));
}
printf("%d",sum);
Input Z should give me output 26, and AA should give 27. But my code gives 26 on both. Thereafter output is always 1 less than what should be the correct output; BC gives 54 instead of 55.
Someone help me out.
Try changing the summation to this:
sum = sum * 26 + ascCol[i]
This avoids having to worry about unexpected floating point rounding behaviour and other issues caused by the fact that pow returns a floating point number.
Note you can simply your entire program to just this:
#include <stdio.h>
int main()
{
char str[5];
scanf("%s", str);
int i = 0;
int sum = 0;
while(str[i] >= 'A' && str[i] <= 'Z')
{
sum = sum * 26 + (str[i] - 'A');
i++;
}
printf("%d", sum);
return 0;
}