working with bits and bytes in c - c

I've checked the questions that were already posted and couldn't quite find the solution to my problem...
I'm making a console program that inputs 2 variables: 1 is a byte and the other is a number of the bit I need to get from that byte using only masking and if statements.
int E1 () {
unsigned char a, b, c;
printf("Number (byte):");
scanf("%d", &a);
a= (unsigned char)a;
printf("\n Bit you want to output (between 0 and 7) :");
scanf("%d", &b);
b=(unsigned char)pow((float)2.0,b);
printf("Mask is: %d", b);
c= a & b; //<-- This returns 0
if (c>0) {
printf("\n\nThe bit is: 1");
}
else {
printf("\n\nThe bit is: 0");
}
return 0;
}
I've asked my teacher and he said that it should work fine. I've tried it and it doesn't work. He is using Visual Studio Express, the free version one can get from Microsoft website and I'm using Code::Blocks (in case this makes a difference in the results).I've added a comment to where I think the problem lies but not sure.
Can anybody please help me with this. Thanks in advance.

Use 1<<b as the mask. Not only is it idiomatic, it's also hugely more efficient than using floating-point calculations. So delete this line:
b=(unsigned char)pow((float)2.0,b);
And set c like this:
c = a & (1<<b)
Does that work any better?

Some testing tells me it's this part that's wrong:
scanf("%d", &a);
This is in fact undefined behavoir: it may or may not work, but you can't really rely on anything. This is because while a is only a 1-byte char, while %d expects a 4-byte integer, meaning that scanf writes four bytes of memory instead of one.
This has the unfortunate side effect that the second call (to scanf("%d", &b)) might use the memory where some other variables in your program are stored, in this case, a. This gets overwritten and set to 0, leading to the expression 0 & b which of course evaluates to 0.
The proper way to solve this problem is to use %hhd instead of %d, which makes scanf expect a char instead of an int, and only write 1 byte of memory.
Side notes about your code
The line a = (unsigned char) a; is useless, since a is already of type unsigned char.
As Graham noted in his answer, you should use b = (1 << b); when calculating powers of two, since this is much more pretty code and also much more efficient — many modern CPUs can do this in just one instruction.

printf("The bit is: %d", 1 & a>>b);

Related

why the output in the terminal is different when i put Prefix -- and a-1

#include <stdio.h>
int sum(int a);
int main()
{
int a;
printf("Enter a value: ");
scanf("%d", &a);
printf("%d", sum(a));
return 0;
}
int sum(int a)
{
if (a == 1)
{
return 1;
}
return a + sum(a - 1);
}
When the input is 5 the output is 15 (which is right),
but when the return is, return a + sum(--a);
(for the same input 5) the output is 11
The behaviour of a + sum(--a) is undefined. The compiler has a lot of freedom as to when and how often it reads a, and when and how often it modifies a. Avoid both reading and modifying the same variable in an expression.
When you wrote
a + sum(a - 1)
, a rough translation of that C code into English is:
"Take a plus the result of the sum function applied to the quantity a-1."
That makes sense, and it's just what you want.
If, on the other hand, you write
a + sum(--a)
, now what you're saying is,
"Take a plus the result of the sum function applied to, hang on a minute, I want to take the variable a minus 1 and assign it back to a and then, where was I, pass it to sum()."
Is that really what you want to do? Why would you want to modify a's value in the middle of calling sum()? You wouldn't want to do that, you don't need to do that, that has nothing to do with the problem of calling sum(a - 1). So don't write it that way. It's confusing to you and me, and what's worse, it's so confusing that the compiler can't figure it out, either. It's so confusing that it's undefined behavior, meaning that the compiler isn't even required to figure out what you mean, and the compiler is explicitly allowed to fall back and punt, and compile your program into something that doesn't work — which is precisely what you discovered when you tried it.
See the canonical SO question Why are these constructs using pre and post-increment undefined behavior? for much (much!) more on undefined expressions like these.

If statement not working in c, section within if statement always runs

I am working with an array and am trying to find the first non zero value in the row focus, but when the program runs it says the first value in the row is not zero even when it is. Here is the section of the code that is not working:
leadingIsHere = 0;
goThrough = 0;
while(leadingIsHere == 0)
{
printf("Before, leadingIsHere: %d, goThrough: %d, array[focus][goThrough]: %lf\n", leadingIsHere, goThrough, array[focus][goThrough]);
if(array[focus][goThrough] != 0)
{
printf("It is happening and array[focus][goThrough]: %lf\n", array[focus][goThrough]);
leadingIsHere = 1;
leading = goThrough;
}//end of if
printf("After, leadingIsHere: %d, goThrough: %d, array[focus][goThrough]: %lf\n", leadingIsHere, goThrough, array[focus][goThrough]);
printf("Focus: %d, leading:%d, goThrough: %d array[focus][goThrough]: %lf\n", focus, leading, goThrough, array[focus][goThrough]);
goThrough++;
}
The printf's are just so I can actually see what all the values I'm working with are, and they show that at all points the value of array[focus][goThrough] is zero, but the part in the if statement still runs. Any help would be very appreciated, thank you.
Here's a formal answer, expanded from the comments section, following discussions therein...
The format used in your printf calls (using %lf) suggests that your array variable is of double type! But be aware: comparing floating-point variables for an exact match is very often problematical (see here: Is floating point math broken?). Thus, the test if (array[focus][goThrough] != 0) may very well fail if the array element being compared to zero is not quite zero.
Further, your output 'check' will not pick this up, as the %lf format will display the value in fixed-format notation, like 0.000100; this will be OK for values >= 0.0000005 but, if you use this for a value of, say, 1.0e-12, it will 'round' the value to 6 decimal places and display 0.000000 - so you will not spot the error.
However, if you use the %lg format, then the printf function will used fixed-format when that will suffice, but use scientific notation if that's the better way to display the result (reasonably) accurately. If you try this, you will probably see that your array values have very small but not zero values (e.g. 5.4e-200, or some such).
To resolve the issue, you should test to see if your array element (or, to be precise, its magnitude) is greater than a pre-defined, very small value; like this, for example:
const int tolerance = 1.0e-20; // Set to a value small enough to be "considered" zero
if (fabs(array[focus][goThrough]) > tolerance) // Use "fabs" to handle negative numbers
{
//... Your code
}
Feel free to ask for further clarification and/or explanation.
EDIT: As suggested by Jonathan Leffler, it is generally better to use a 'relative difference' function rather than a fixed value for tolerance (which I have used here for simplicity/brevity).

Reading boolean with fscanf

Today I encountered a problem with scanf functions. Assume that you have a structure like the following example.
struct structA{
bool bVal;
int nVal;
}
If you run the following code
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
fscanf(fp,"%d",&a.bVal);
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
It will print
a.bVal = 0
a.nVal = 0
The reason is that the fscanf function assumes a.bVal is an integer and overwrites the a.nVal first 3 bytes. This problem can be solved by the following dirty solution.
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
int nBVAL;
fscanf(fp,"%d",&nBVAL);
a.bVal = nBVAL;
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
My question is that is there a cleaner and straightforward way of avoiding this problem beside the solution explained?
The solution you're proposing is the only portable one.
There is no conversion specifier for _Bool. There's also no guarantee about the storage size of a _Bool, except that it has at least CHAR_BIT bits. Even if you knew the size and tried something like %hhd, entering anything other than 1 or 0 would create a value that's invalid for a _Bool (scanf() would access the object through a char pointer, possibly writing the padding bits of the _Bool).
The only safe thing to do is to take input of a type you can handle and convert this to a _Bool where needed, as you're doing in your example.
Note there's no similar problem with printf(). A _Bool passed to printf() is promoted to int, so %d is fine.

Wondering how to add arrays of vectors?

I need to add two vectors in the arrays together. For example my code should execute the vector = {3,6,9}.
I dont really know what I did wrong as I am still new to coding. So any help is appreciated!
void add_vectors( double vector1[3]={1,2,3},double vector2[3]={1,2,3},double
vector3[3]={1,2,3}, int n)
{
n=sizeof(vector1);
int i;
for(i=0; i>n; i++)
{
scanf("%f", &vector1[i]);
scanf("%f", &vector2[i]);
vector3[i]=vector1[i]+vector2[i];
}
printf (vector3[]);
Sorry for the bad formatting but it's my frist time using this site.
There are several mistakes here in the code:
First, sizeof() gives you a size of something in a memory (in bytes), which is probably not what you desire.
Secondly, i>n statement means that the loops will execute only while i > n! The first time i = 0, and n is a positive integer. That means that the loop will be skipped, since i is not larger than n.
Third, printf() does not work like this.
I explained you the second point; my first and third points are widely explained on the internet: try finding these answers yourself.

Can anybody explain the error in the program i made, can anybody why i didn't workout?

how is your day :),
Take a look at the below program, the program written below is to calculate the sum of first n natural numbers, the problem is that i get the sum of n-1 natural numbers, can anybody explain why ?
and can anybody also explain why a-- instead of --a.
#include<stdio.h>
main()
{
int a,sum;
printf("Enter a number.");
scanf("%d",&a);
sum=sumnat(a);
printf("Sum of the first %d natural numbers is %d.",a,sum);
}
sumnat(a)
{
int b;
if(a==0)
{
return 0;
}
else
{
b=a+sumnat(--a);
return(b);
}
}
There were several errors, the greatest of which was undefined behaviour in the expression which uses a and also a modified value of a. You should also define your function properly, not rely on default values provided by the compiler.
#include <stdio.h>
int sumnat(int a); // function prototype
int main(void) // correct signature
{
int a, sum;
printf("Enter a number. ");
scanf("%d", &a);
sum = sumnat(a);
printf("Sum of the first %d natural numbers is %d.", a, sum);
return 0;
}
int sumnat(int a) // function has a return type and argument type
{
if(a == 0)
{
return 0;
}
return a + sumnat(a - 1); // there was no need to decrement `a`
}
Program session
Enter a number. 5
Sum of the first 5 natural numbers is 15.
Your program works for me, using gcc on Mac OSX. However, it will not work everywhere, because of this line:
b=a+sumnat(--a);
--a decrements a, but if it does so before the addition, then your result will be wrong. I'm not sure C is required to evaluate expressions strictly left-to-right (I don't think it is). At any rate, since you don't use a after that line, you could fix things this way:
b=a+sumnat(a-1);
As #self says, you should fix the program to handle negative values, and it would be a good idea to consider what is the largest natural number whose sum you can compute this way (and why that is).
There is a difference between them. One first subracts from a and than goes in the function while the other frist goes in... so it never gets subracted and you go to inifinit stack.
"and can anybody also explain why a-- instead of --a"
When you use the prefix operator --a the decrease is done before anything else, while the postfix operator a-- happens after the rest of the expression is resolved, so, lets say, while debugging your code, in a particular moment, a = 5
since the line
b=a+sumnat(--a);
is using the prefix version of the operator, the decrement would happen immediately, making a=4 and then the function sumnat would be called with argument 4
b=a+sumnat(a--);
in this case the postfix operator is being used, so first the function sumnat would be called with the argument 5, since that is the value of a in that moment, then, only when the function returns a value (which would never happen in your example, since it would be called multiple times with the same value, never reaching 0) the decrement would happen

Resources