LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-13-2019, 05:08 PM   #376
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194

Quote:
Originally Posted by jsbjsb001 View Post
But I'm still a little confused as whether I'm just changing the value of, and in this case, the variable "value", or if I'm actually doing more than ? And while I tried reading Wikipedia for one about exactly what a "word" actually means, I'm not sure that's real clear to me. The only thing I'm getting from what I've read is that it's "a unit of data", which isn't clear to me.
Bit manipulations are just another way to operate on, or manipulate a value, specifically the binary representation of that value. In base ten, shifting all the digits to the left one place by adding a zero on the right is numerically the same as multiplying by ten. In base two, binary, shifting all the digits to the left one place by adding a zero on the right is numerically the same as multiplying by two. See the pattern?

Code:
123 base ten - shift left 1 place = 1230 
111 base two - shift left 1 place = 1110
Numerically we could continue this indefinitely, but our computing machines have a physical limit to the number of digits they can work with directly in a single operation, and those digits are always binary and called bits (i.e. BInary digiTS, or BITS). Consequently, when we left or right shift one bit the respective highest or lowest bits before the shift, falls out onto the floor - gone forever!

As far as the meaning of "word", I too, have found that confusing at times, and have seen it used to mean both a 16-bit wide register and the width determined by the architecture, and also sometimes disambiguated by terms like 32-word and 64-word. Ntubski's post is probably an accurate summary of the why and wherefore of that. In all cases though, it is really just a reminder that we are always working with some fixed bit-width representation of values, so try keep that thought in mind.

By the way, the part of the little program previously mentioned could have been written entirely using only bitwise operations, but at the time written it was intentionally limited to using concepts already introduced in your book to that point, and the focus was on the math. Doing it with bit operations may simplify it, and would still be doing the math, only in a different but completely equivalent and often more efficient way. The exercise of doing that would provide an excellent opportunity for you to see again the direct connection between the math and the mechanics of programming! Highly encouraged, and now would be an excellent time!

Good progress by the way! Keep it up!

Last edited by astrogeek; 04-13-2019 at 09:59 PM. Reason: tpoys and added comment
 
1 members found this post helpful.
Old 04-14-2019, 03:08 AM   #377
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
Thanks for that RT, it makes it a lot easier to try and decipher what the 1's and 0's are saying!

Thanks a lot for that ntubski, you've been a great help. As your explanation in post #375 is by far the best one I've seen, so I think that answers my question. Thanks again!

Thanks for your help astro! From what I can see it adds a zero on the end, but that's the only pattern I can really see. I do sorta see what you mean (I *think*) by it numerically being the same as multiplying by two. But I can't say I completely understand, other than what has been said before your latest post.

I've tried to adjust that program you wrote for me to use bitwise operators instead, and I do seem to be getting correct answers from it. Some of it I couldn't figure out which bitwise operator I needed, as while what it says in the C book combined with some practice, and what you guys have explained does seem to make sense for the very most part, I'm still by no means an expert at it yet. I tried to keep the original formatting/indentation so it would be easier for ya's to see what I've changed.

I posted the modified code below;

Code:
#include <stdio.h>
int main(void){
        unsigned int x, pow2;
        while(1){
                printf("\nEnter a positive integer to convert (0 to exit): ");
                scanf("%i",&x);
                if(x == 0)  
                        break;
                if(x<0){
                        printf("Not a positive number!\n");
                        continue;
                }
                printf(
"\nBase 10     Base 8     Base 16    Base 2     \n\
(Decimal)   (Octal)    (Hex)      (Binary)   \n\
=========   =======    =======    ===========\n");
                printf("%-12i%-12o%-12X", x, x, x);
                for(pow2=1;;)  
                        if(pow2 <<= x) // <-- seems to be correct(?), but with an extra zero at the front
                                break;
                while(pow2 <<= 0){ // <-- seems to be correct(?), but with an extra zero at the front
                        if(x<pow2)
                                printf("0");
                        else
                                printf("1"), x-=pow2;
                        pow2 /= 2;
                }
        }
        printf("Bye!\n");
        return 0;
}
 
Old 04-14-2019, 06:15 AM   #378
jpollard
Senior Member
 
Registered: Dec 2012
Location: Washington DC area
Distribution: Fedora, CentOS, Slackware
Posts: 4,912

Rep: Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513Reputation: 1513
Note:

pow2 <<= x

means to shift the value of pow2 by x bits... and then store the shifted value back in pow2.

Normally this would NOT be done as a condition, it is permitted, but it also sometimes causes confusion because the modification of pow2 may not be what you want.

pow2 <<= 0

means shift the value of pow2 by nothing... and then store it back. The result is do nothing.
 
2 members found this post helpful.
Old 04-14-2019, 07:11 AM   #379
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,780

Rep: Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081
Quote:
Originally Posted by jsbjsb001 View Post
Code:
                for(pow2=1;;)  
                        if(pow2 <<= x) // <-- seems to be correct(?), but with an extra zero at the front
                                break;
If x is greater than or equal to 32 (or whatever number of bits unsigned int happens to be), that shift causes undefined behaviour.

(In fact, just reading the code I had at first assumed it would loop infinitely, but it turns out that on x86 x's value is reduced mod 32 first)

https://stackoverflow.com/questions/...-width-of-type
 
2 members found this post helpful.
Old 04-14-2019, 08:03 AM   #380
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,804

Rep: Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306
this code will/may go into infinite loop depending on the input (for me when I entered: asd).
the return value of scanf should also be checked.
the number of leading zeros depends on the input too:
Code:
Enter a positive integer to convert (0 to exit): 1

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
1           1           1           01
Enter a positive integer to convert (0 to exit): 2

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
2           2           2           010
Enter a positive integer to convert (0 to exit): 432

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
432         660         1B0         00000000110110000
Enter a positive integer to convert (0 to exit): asd
<infinite loop>
 
1 members found this post helpful.
Old 04-14-2019, 07:40 PM   #381
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
I am not sure why you did it that way, other than a shot in the dark, maybe? But as shots in the dark go, at least you used the right weapon, even if your aim was a little wild!

Consider points made by jpollard and ntubski, they pretty much cover the problems with that.

Quote:
Originally Posted by pan64 View Post
this code will/may go into infinite loop depending on the input (for me when I entered: asd).
the return value of scanf should also be checked.
the number of leading zeros depends on the input too:
Yes, good catch. At the time written I was trying to constrain the wide-ranging discussion to the flow of the book the OP was using as a guide. The approach of the book was to introduce simple concepts, then lead the student to bump into potential problems and fixes in later chapters. I wrote this program specifically to use only ideas introduced to that point in the book, which included the naive use of scanf for integer input.

Now that we have bumped into that problem, we should understand it and fix it! So, jsbjsb001, your assignment for the afternoon is to search online for why this use of scanf is a problem, and how can we avoid it! Let us know what you find out, and ask us for comment at that time! (aka, Ball in your court!)

As for the bitwise implementation of a binary output routine, here is one possible approach which should work with existing varible names:

Code:
for(pow2=1;pow2<(x&~pow2);pow2<<=1);
for(;pow2>0;pow2>>=1)
    printf("%i", (pow2&x)!=0 );
This also solves the inconsistent leading zero output pointed out by pan64. Do you see why it happens in the original code? Why does it not happen in this one? Hint: Consider the behavior with 3,4,5 and 7,8,9... see anything special about those?

Finally, as you have now read about functions and c-strings and pointers, think about making the binary conversion a function which would write the binary output to a sting. Try to write it such that you can use the function call as a parameter to printf instead of as a trailing block of code.

Extra points to make it print the binary output in four bit groups to help you visualize it as hexadecimal (review your recent posts on topic).

Last edited by astrogeek; 04-15-2019 at 12:12 AM. Reason: Added comments, more tpoys, tyop
 
1 members found this post helpful.
Old 04-15-2019, 01:00 AM   #382
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
Thanks again guys!

Hopefully it will make sense to me one day, it's a credit to you guys for sticking with me - as I could understand if you guy's considered me a lost cause.

Quote:
Originally Posted by astrogeek View Post
So, jsbjsb001, your assignment for the afternoon is to search online for why this use of scanf is a problem, and how can we avoid it! Let us know what you find out, and ask us for comment at that time! (aka, Ball in your court!)
From what I've read, the only thing I can see that would be related to the code in question, is that: if I typed in a bigger enough number, then some of it would get "lost" and therefore be undefined (if greater than or equal to 32, as ntubski said - although, I'm not clear on why tho), and therefore the program would not give the correct result? Or if I typed in a char, it would not handle this situation properly (or a string that was long enough) ? Beyond that I'm honestly not sure, I wasn't even 100% sure exactly what I was really searching for as far as the search terms I used. I found the following links, and it was the first link that made the most sense to me, but in a lot of cases, they talked about scanf's use with char's and not integers - so I'm not sure exactly what the problem is to be honest. I did try reading the points made by jpollard and ntubski, but I'm not exactly sure what they mean exactly beyond what they said (what they said does make sense in itself, but I'm not sure about it beyond that). Sorry in advance if I don't make sense - I'm not sure how else to explain my thinking.

https://www.quora.com/Why-is-scanf-i...harmful-or-bad
https://www.geeksforgeeks.org/bitwis...tors-in-c-cpp/

Quote:
Do you see why it happens in the original code? Why does it not happen in this one? Hint: Consider the behavior with 3,4,5 and 7,8,9... see anything special about those?
No, I'm not honestly sure why it's happening, I'll guess that it was "shifting" an extra place each time the number got bigger?

In the case of "3" it's adding an extra zero to the output? In the case of "4" it's adding 2 extra zero's to the output? In the case of "5" it's adding 3 extra zero's to the output? In the case of "7" it adds 5 extra zero's to the output? So basically, the bigger the number entered, the more extra zero's that are added to the output is what I'm seeing.

Quote:
Try to write it such that you can use the function call as a parameter to printf instead of as a trailing block of code.
I'll see what I can do, but I might wait to see if my above thinking is right or not. I'm not confident about making it print the binary output in four bit groups tho. But that would be very helpful to visualize it, if I can do that tho.
 
Old 04-15-2019, 01:40 AM   #383
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
Quote:
Originally Posted by jsbjsb001 View Post
From what I've read, the only thing I can see that would be related to the code in question, is that: if I typed in a bigger enough number, then some of it would get "lost" and therefore be undefined (if greater than or equal to 32, as ntubski said - although, I'm not clear on why tho), and therefore the program would not give the correct result?
It isn't that some of it would get lost. The problem is that it makes no sense to shift by the value of x and doing so may lead to undefined behavior at worst, a useless result at best.

If the size of an integer is 32 bits, and the number you input is greater or equal to 32 - then you have shifted the whole thing out onto the floor! If it is less than 32 it still produces no useful result - it simply isn't the right thing to do here.

Jpollard also points out that you are using the shift operator inside a conditional test. While the language allows that, it makes no sense to do it as shown. So the real question you need to ask yourself is what you were expecting it to do - how were you expecting it to work?

It appears to me that you were simply trying to replace the arithmetic operators with bit-shift operators, and that doesn't work.

Quote:
Originally Posted by jsbjsb001 View Post
No, I'm not honestly sure why it's happening, I'll guess that it was "shifting" an extra place each time the number got bigger?

In the case of "3" it's adding an extra zero to the output? In the case of "4" it's adding 2 extra zero's to the output? In the case of "5" it's adding 3 extra zero's to the output? In the case of "7" it adds 5 extra zero's to the output? So basically, the bigger the number entered, the more extra zero's that are added to the output is what I'm seeing.
You must be seeing that with your code above? But that doesn't work the way you think anyway, as already noted.

I was actually referring to the way the original code worked.

What I am seeing, and presumably what pan64 meant (please correct me if I am wrong!) is that some numbers are printed in binary with a leading zero, others are not. The ones that include a leading zero are not an even power of two, the ones without a leading zero are. The reason is in the condition I used to find the highest power of two. The above bitwise code block should work the same way if you change the (x&~pow2) to a naked x, I think.
 
1 members found this post helpful.
Old 04-15-2019, 05:22 AM   #384
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
Quote:
Originally Posted by astrogeek View Post
...
It appears to me that you were simply trying to replace the arithmetic operators with bit-shift operators, and that doesn't work.
...
I figured if a "left shift" means multiply by 2, then it would be the same as saying whatever * 2, but I was obviously wrong about that. But yes, beyond what's already been said, it's not really 100% clear what I'm actually doing, by doing that.

Quote:
You must be seeing that with your code above? But that doesn't work the way you think anyway, as already noted.
Yes, and like I said above and as said, I was wrong in my thinking.

Quote:
I was actually referring to the way the original code worked.
...
Sorry, I must have gotten confused. Sorry about that.

Anyway I tried what you said before about creating a function for the binary output. While my function does get called, and does return a value, it looks like I've broken your program yet again, and it's adding extra zero's again. I have no idea what the problem is, let alone how to get it to display the binary output in groups of 4. But it's only the binary output that's broken, the rest of the outputs look fine. And it does exit on typing in "0", and doesn't loop forever.

Here's the code below;

Code:
#include <stdio.h>
int binaryOutput(int x);
int main(void){
        int x;
        while(1){
                printf("\nEnter a positive integer to convert (0 to exit): ");
                scanf("%i",&x);
                if(x==0)
                        break;
                if(x<0){
                        printf("Not a positive number!\n");
                        continue;
                }
                printf(
"\nBase 10     Base 8     Base 16    Base 2     \n\
(Decimal)   (Octal)    (Hex)      (Binary)   \n\
=========   =======    =======    ===========\n");
                printf("%-12i%-12o%-12X", x, x, x);

	printf("%i", binaryOutput(x));
	}
	printf("Bye!\n");
        return 0;
	}
	
                
int binaryOutput(int x) {

int pow2;    
                for(pow2=1;;pow2 *= 2)
                        if(pow2 >= x)
                                break;
                while(pow2>0){
                        if(x<pow2)
                                printf("0");
                        else
                                printf("1"), x-=pow2;
                        pow2 /= 2;
                }
               
                return x;
       
}
Here's some output's of it;

Code:
Enter a positive integer to convert (0 to exit): 1

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
1           1           1           10
Enter a positive integer to convert (0 to exit): 2

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
2           2           2           100
Enter a positive integer to convert (0 to exit): 3

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
3           3           3           0110
Enter a positive integer to convert (0 to exit): 4

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
4           4           4           1000
Enter a positive integer to convert (0 to exit): 0
Bye!
[james@jamespc math-helpers]$ ./bases_binaryFunction 

Enter a positive integer to convert (0 to exit): sfegge
Bye!
[james@jamespc math-helpers]$ ./bases_binaryFunction 

Enter a positive integer to convert (0 to exit): asd
Bye!
 
Old 04-15-2019, 01:47 PM   #385
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
Quote:
Originally Posted by jsbjsb001 View Post
I figured if a "left shift" means multiply by 2, then it would be the same as saying whatever * 2, but I was obviously wrong about that. But yes, beyond what's already been said, it's not really 100% clear what I'm actually doing, by doing that.
The right idea, but very imprecise. You must learn to think and code with precision.

First, left shift does not mean multiply by two. Left shift by one bit does mean multiply by two, and it is exactly equivalent - you can use integer "left shift by one bit" anywhere you can use integer "multiply by two", with (mostly) the same limitations imposed by the size of the thing being shifted or multiplied. That is an important concept to grasp and you should explore it further to understand the limitations a finite number of bits imposes on each operation.

BUT! Your code does not left shift by one bit, and therefore does not multiply by two!

Code:
if(pow2 <<= x) // <-- seems to be correct(?), but with an extra zero at the front
Your code left shifts by x number of bits. The point being made by others is that this makes no sense. So if you intended to multiply by two, you have not written code which does that. And because the following code depends on the value of pow2 being a highest power of two in the value of x, it will not work as expected.

The reason for the growing number of leading zeroes is because you are starting from 'x' number of places to the left, which is not what is needed.

Quote:
Originally Posted by jsbjsb001 View Post
Yes, and like I said above and as said, I was wrong in my thinking.
So you need to pause and understand why in order to progress.

One thing I have seen you do repeatedly is to write code without testing that it does what you expect. We all do that, but learning to not do that is an essential programming skill. This is not debugging, it is simply making the first effort to assure that each part of the code behaves as expected. Like a house painter looking at their work as they paint to make sure they covered a given area. Not doing so is like a painter wearing a blindfold... take off the blindfold!

You could have quickly tested whether it behaved as expected by writing an isolated test case - make the habit of doing that. And you should do that now whether you end up using the code or not - explore how that bit of code behaves so that you will know what to expect next time you see it.

Quote:
Originally Posted by jsbjsb001 View Post
Sorry, I must have gotten confused. Sorry about that.

Anyway I tried what you said before about creating a function for the binary output. While my function does get called, and does return a value, it looks like I've broken your program yet again, and it's adding extra zero's again. I have no idea what the problem is, let alone how to get it to display the binary output in groups of 4. But it's only the binary output that's broken, the rest of the outputs look fine. And it does exit on typing in "0", and doesn't loop forever.
Well, you have written a function, but not one that works anything like what I suggested.

Please read what I suggested again and pay attention to the elements it should use to get the desired behavior... here is the essential behavior I described as seen from the calling viewpoint:

Code:
printf("%-12i%-12o%-12X%-s", x, x, x, binaryConvert(x));
How would you do that?

Last edited by astrogeek; 04-15-2019 at 04:34 PM. Reason: clarity, integer multiply, convert
 
2 members found this post helpful.
Old 04-16-2019, 12:42 AM   #386
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
Quote:
Originally Posted by astrogeek View Post
The right idea, but very imprecise. You must learn to think and code with precision.

First, left shift does not mean multiply by two. Left shift by one bit does mean multiply by two, and it is exactly equivalent - you can use integer "left shift by one bit" anywhere you can use integer "multiply by two", with (mostly) the same limitations imposed by the size of the thing being shifted or multiplied. That is an important concept to grasp and you should explore it further to understand the limitations a finite number of bits imposes on each operation.
I understand what you're saying, but I'm honestly not sure how to even begin trying to explore it.

Quote:
BUT! Your code does not left shift by one bit, and therefore does not multiply by two!

Code:
if(pow2 <<= x) // <-- seems to be correct(?), but with an extra zero at the front
Your code left shifts by x number of bits. The point being made by others is that this makes no sense. So if you intended to multiply by two, you have not written code which does that. And because the following code depends on the value of pow2 being a highest power of two in the value of x, it will not work as expected.

The reason for the growing number of leading zeroes is because you are starting from 'x' number of places to the left, which is not what is needed.
While for the most part I see what you're saying, I'm not exactly sure I completely understand about the reason for the leading zeroes, other than I did it in the wrong way.

Quote:
So you need to pause and understand why in order to progress.
I'm not honestly trying to be a smartass or anything, but I don't understand why, and as said above, I'm not sure how I'm supposed to understand it. I tried reading the C book, various sites, but it just isn't making complete sense to me. I don't know how to explain any better than that - I would if I could.

Quote:
One thing I have seen you do repeatedly is to write code without testing that it does what you expect. We all do that, but learning to not do that is an essential programming skill. This is not debugging, it is simply making the first effort to assure that each part of the code behaves as expected. Like a house painter looking at their work as they paint to make sure they covered a given area. Not doing so is like a painter wearing a blindfold... take off the blindfold!
I did test it, but obviously not enough.

Quote:
You could have quickly tested whether it behaved as expected by writing an isolated test case - make the habit of doing that. And you should do that now whether you end up using the code or not - explore how that bit of code behaves so that you will know what to expect next time you see it.
I did what you said, and tested the binary output by itself, but I honestly don't know why it's giving me a leading zero.

Code:
#include <stdio.h>

int main(void) {
  
    int pow2, x; 

    puts("Enter a number: ");
    scanf("%i", &x);
                                 
                for(pow2=1;;pow2 *= 2)
                        if(pow2 >= x)
                                break;
                while(pow2>0){
                        if(x<pow2)
                                printf("0");
                        else
                                printf("1"), x-=pow2;
                        pow2 /= 2;
		}
		
		printf("\n");
               
                return 0;
       
}
This is the output;

Code:
[james@jamespc math-helpers]$ ./binary 
Enter a number: 
6
0110
Quote:
Well, you have written a function, but not one that works anything like what I suggested.

Please read what I suggested again and pay attention to the elements it should use to get the desired behavior... here is the essential behavior I described as seen from the calling viewpoint:

Code:
printf("%-12i%-12o%-12X%-s", x, x, x, binaryConvert(x));
How would you do that?
Other than maybe, and I'm guessing an array for the binary output, I'm honestly not sure why it isn't working. I tried the line you posted above to see if I could at least get it to give the correct binary output, and I got the following error, which I know is because "s" is for a "string" and not an int - as the error from gcc says. I tried replacing it with an "i" for an int, and now depending on the input, it either displays the binary output where it's supposed to display the decimal number, or puts it in an infinite loop.

So I honestly have no idea how to fix it. Maybe I should just move on instead, I'm sorry, but it seems no matter what I try, I hit yet another roadblock. I can see what the code is doing, but I don't honestly know why it's doing it (even how it correctly figures out the correct binary conversion). I honestly don't know why it's doing the maths it is, other than that's how it figures out the binary number.

Code:
[james@jamespc math-helpers]$ gcc -Wall -Werror bases_binaryFunction.c -o bases_binaryFunction
bases_binaryFunction.c: In function ‘main’:
bases_binaryFunction.c:25:3: error: format ‘%s’ expects argument of type ‘char *’, but argument 5 has type ‘int’ [-Werror=format=]
   printf("%-12i%-12o%-12X%-s", x, x, x, binaryOutput(x));
   ^
cc1: all warnings being treated as errors
And this is what happens when I change "s" to an int;

Code:
[james@jamespc math-helpers]$ ./bases_binaryFunction 

Enter a positive integer to convert (0 to exit): 5

Base 10     Base 8     Base 16    Base 2     
(Decimal)   (Octal)    (Hex)      (Binary)   
=========   =======    =======    ===========
01015           5           5           0
And if I type in "asd" (or any other bogus value) after than, it just keeps looping the same result again.
 
Old 04-16-2019, 09:19 AM   #387
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,883
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
This started with a question about bit shifting.

There are a large number of very lengthy posts about it, including a lot of code, and what seems to be a huge confusion about it.

I'm left thinking, "How did this get broken from a week or so ago when you seemed to understand the fundamental points?"

What exactly is your current question, in ten words or less?
 
1 members found this post helpful.
Old 04-16-2019, 09:59 AM   #388
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
I honestly don't know RT - I'm almost just as confused as when I asked about bit shifting before. I'm not even sure what question to ask now.

But I guess while I'm here I may as well ask: does "value << 1" mean left shift one bit. As in: does the "1" just mean shift one bit, as in, when astrogeek says "Left shift by one bit does mean multiply by two, and it is exactly equivalent - you can use integer "left shift by one bit" anywhere you can use integer "multiply by two", with (mostly) the same limitations imposed by the size of the thing being shifted or multiplied." in post #385 ?

I also had another look at how to get the function for the program astrogeek wrote me, that he talked about in post #381, about putting the binary output in 4 bit groups, and using a function for the binary output of it, but I still have no idea what I've done wrong. I tried to do it without the bitwise operators and printing it in 4 bit groups, to try and at least fix the problem of the leading zeros - but as I said above, I've just ended up breaking it even more. So at this point, I don't know what to do. Thanks for all your help, and everyone else's help too.
 
Old 04-16-2019, 10:06 AM   #389
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,883
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
Quote:
Originally Posted by jsbjsb001 View Post
does "value << 1" mean left shift one bit
Yes it does. You've seen that in code which I showed in a post and you copied, and extended, with great effect. Why is it still a question?

Bear in mind. I'm not trying to be an antagonist or be mean spirited about it. I'm saying that this concept is pretty simple, and that you can test it. In fact, you have tested it.

Yes, like any subject, you can go too far. Why worry about it now? Or also, why is the subject of going to far with a shift something beyond your grasp? You've talked about word size, and intelligently so. Therefore you should be able to fully grasp that if you specified some code that performed a left shift by 100 bits that it would be beyond the size of a word in your system, in many systems, and therefore the bit shifted would be out of existence as far as your program knew or cared about it.

This concerns me because this is a pretty simple topic and it really shouldn't be something to frustrate you so that you start down-talking about yourself.

Back to the basics. You copied and modified a program which did (value << 1), and more and witnessed the outcome. You got the concept. "NEXT!"

Last edited by rtmistler; 04-16-2019 at 10:20 AM.
 
2 members found this post helpful.
Old 04-16-2019, 10:14 AM   #390
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth, unfortunately...
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881

Original Poster
Rep: Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063Reputation: 2063
I guess the way astrogeek was saying it, it made me wonder if I was understanding what he was saying correctly, and by extension, understanding "left shifting by one bit". And also the problems I had with trying to use bitwise operators in that program astrogeek wrote me before. But thanks for clearing that up for me and your help RT.
 
  


Reply

Tags
c programming, learning c



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Finally decided to try to get libinput to work Timothy Miller Linux - Hardware 3 01-04-2018 08:04 PM
Decided to try Lubuntu 14.04 on my netbook... pcninja Ubuntu 4 04-20-2014 08:18 PM
Finally decided to get serious & learn a302svt LinuxQuestions.org Member Intro 1 07-19-2007 12:27 PM
Decided to try Debian some guidance required ninadb Debian 2 08-20-2004 11:40 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:42 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration