#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    10
    Rep Power
    0

    Int to Short and Two's complement


    Hello guys.i have a question that is a bit low level and i dont know if i should have posted it here but i will give it a try.
    I know that a number is stored using two's complement.
    Also i know when c copies a number that is stored in an int variable(4 bytes) to a short variable(2 bytes) i know that the THIRD byte of the INT variable will go to the FIRST byte of the SHORT variable and the FOURTH byte of the INT variable will go to the SECOND byte of the SHORT variable.
    Well i store -32768 in an INT variable.
    The binary for this using two's complement is:
    11111111 11111111 01111111 11111111
    Then i put this value to a short variable without any type casting or anything
    So according to the way C copies data
    short binary should be --> 01111111 11111111
    which in decimal is 32767.
    BUT when i print the short variable using printf it prints the correct value -32678
    What happens?
    Please i am new to computer science so easy on me..
    Thanks for your time
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,151
    Rep Power
    2222
    Are you sure that that is what's stored in that short variable? You should verify that either with a debugger or by printing the variable in hex with "%X".

    Also, just exactly how are you storing the lower two bytes of the int into the short? If you are simply assigning it, then C will perform an implicit conversion. So if you print it out in hex, you are expecting 0x7FFF, but I think you'll get 0x8000 instead.

    If you use bit-wise operators, you should be able to get the results that you want. Also, you could use pointers or a union to explicitly copy the individual bytes over, though you need to be aware of your system's byte order -- if it's an Intel box, then it would be little-endian.

    PS
    Also, the binary representation of -32768 is 11111111 11111111 10000000 00000000. Your mistake was that you only converted 32768 to its One's Complement form by inverting all the bits. You still need to add one to it to make it the Two's Complement.

    Code:
      11111111 11111111 01111111 11111111    1's Complement
     +00000000 00000000 00000000 00000001      plus 1
      -----------------------------------    ------------
      11111111 11111111 10000000 00000000    2's Complement
    Last edited by dwise1_aol; January 28th, 2013 at 04:46 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    10
    Rep Power
    0
    Actually my question is -->
    Search on youtube for this video
    --> Lecture 2 | Programming Paradigms (Stanford)
    and go to 29:18.
    The question on which the professor says he doesnt knows what it is.You may have to start watching the video from 26:58 to understand the question.
    Also thanks for the reply.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,850
    Rep Power
    481
    You could have written this.
    Code:
    #if 0
    bit    short     int
     12 4097 4097
     13 8193 8193
     14 16385 16385
     15 -32767 32769
     16 1 65537
     17 1 131073
     18 1 262145
     19 1 524289
    #endif
    
    #include<stdio.h>
    int main() {
      int a, i;
      short s;
      puts("bit    short     int");
      for (i = 12; i < 20; ++i) {
        a = (1 << i) + 1;
        s = (short)a;
        printf("%3d %d %d\n",i,s,a);
      }
      return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,151
    Rep Power
    2222
    It could take a few days. We're not allowed to stream at work -- eats up too much bandwidth -- so I'll have to wait until I get home. Tonight I won't get home until after 9PM at which time I need to prepare for work the next day. Tomorrow night I get home even later. Thursday night would be the soonest.

    No hints as to what you're asking?
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,151
    Rep Power
    2222
    Originally Posted by Lan07
    Actually my question is -->
    Search on youtube for this video
    --> Lecture 2 | Programming Paradigms (Stanford)
    and go to 29:18.
    The question on which the professor says he doesnt knows what it is.You may have to start watching the video from 26:58 to understand the question.
    Also thanks for the reply.
    OK, what he doesn't know is what happens when a magnitude bit becomes a sign bit.

    Do you understand the difference between a magnitude bit and a sign bit? Is that the basis of your question?

    Are we talking C here? Or are we talking programming languages in general? Because that adds even more unknowns to this "equation".

    Every programming language has (or should have) a published standard. It is the job of every compiler designer to comply with that published standard. This became a big issue with the early 1980's Department of Defense "do it all" language, Ada*, whose standard required that only a certified compiler could be used and that a certified compiler had to implement the entire language, not a sub-set of the language (plus, each compiler had to be re-certified every six months). For many years, no Ada compiler could do that, so aerospace companies did most of their development work in Pascal, which was superficially similar to Ada (one textbook we used was divided into two parts: Part 1 -- how incredibly like Pascal Ada is; Part 2 -- how incredibly unlike Pascal Ada is.).

    Now, the problem is that the standard does not cover every single possible situation. So when you try something that is not defined by the standard, you have no guarantee what will happen. One example is calling fflush(stdin). The actions of fflush is very well defined for the standard output file, stdout, but not for the standard input file, stdin. Some compilers will flush stdin, but others will not. Teachers will teach fflush(stdin) because they know that it works for the compiler that they use, but if their students then use that with a compiler that does not act the same way, they get a very unpleasant surprise. I forget which forum member has this sig-line, but if you depend on undefined behavior, you are dancing bare-foot on broken glass, so you should expect to get your feet cut to ribbons.

    In C, when you assign a 32-bit int to a 16-bit int, you will get the lower two bytes copied while the upper two bytes are lost. But what happens when a 32-bit signed positive integer that just happens to have the 15th bit set (ie, the sign bit of a 16-bit integer) gets assigned to a short int (ie, a 16-bit int)? Does the language standard handle that situation specifically? If not, then that situation is undefined. So what happens then? It all depends on the individual compiler. So then, "Who knows?"

    To reiterate, if the behavior is not defined by the standard, then what happens depends entirely upon the designer of the compiler. Which can very well change from one compiler to another. So then, who knows?

    {* FOOTNOTE:
    Ada was named for Ada Augusta, Lady Lovelace, patron and correspondent of Charles Babbage. As Babbage was designing his analytic engine, a 19th century mechanical computer whose specifications exceeded the ability of the machinists of the time to build it. Ada wrote programs for that analytic machine, making her history's first ever computer programmer and that was the reason for naming the language after her. The Ada language standard, a military standard, was designated MIL-STD 1815A; 1815 was the year of Ada's birth. The standard is published with a green cover, because the four competitors were designated by color; the green competitor, based on Pascal, is the one that won.

    Interestingly, when computing became a practical reality during World War II with ENIAC, the first programmers were again women. Because men were going into the services to fight, women increasingly entered into work that had previously been occupied only by men. The icon of the age was "Rosie the Riveter", shown with her sleeve rolled up displaying her arm muscle. For the growing work in cryptology (including breaking the German and Japanese cyphers) and in electronic computation (eg, to calculate the gunnery tables for the new weapons), women with mathematical backgrounds were recruited. ENIAC, designed to generate those much needed gunnery tables, had to almost literally be rewired with patch cables and gang switches. It was the women who worked at that level who knew how to rewire that machine for each new application; the men who had designed it could not do the job. And when Eckert and Mauchly left the ENIAC project and created UNIVAC, their first programmers were the women they had worked with on the ENIAC project.

    For more information, if you have access to NetFlix streaming, watch "Top Secret Rosies: Female Computers of WW2". Up to and through the 1940's, a computer was a person, not a machine. Do you drink? Raise a glass in honor of those women.

    One was a young Navy Reserve ensign, Grace Hopper. In 1944, after the officer had given her her orientation in a Navy computer project she had been assigned to, she turned to a petty officer and asked him what was really going on. 30 years later, she retired from the Navy Reserve. During her service, she helped design the COBOL language. She is also known for a teaching aid. She had a technician cut pieces of wire about a foot in length for her to hand out in class. That length is how far an electrical signal will travel in one nano-second. Think about that.
    }


    PS
    The instructor goes on to say that he will run an experiment and email the class on it. Do you have access to that instructor and will you be able to obtain that email? Try to.

    He also points out that all attempts to preserve the sign bit will be done. Pay attention to that and to his answer to you.

    Also be sure to bring up the issue of whether the behavior he's testing for is defined by the standard and will work for all compilers. This is an important issue to keep in mind and may even earn you points if he is one of your instructors. It might even require you to actually look up the standard, so be prepared.
    Last edited by dwise1_aol; January 30th, 2013 at 03:15 AM.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    10
    Rep Power
    0
    Thank you so much dwise1.Your last reply really helped me get some things.Gotta take a look now at the C standard.By the way i dont study at Stanford i study CS(just started not even first year yet) at an another university at an another country and these days i have exams and i couldnt contact my proffessor to ask him.
    Again thank you.
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,151
    Rep Power
    2222
    Originally Posted by Lan07
    Thank you so much dwise1.Your last reply really helped me get some things.Gotta take a look now at the C standard.By the way i dont study at Stanford i study CS(just started not even first year yet) at an another university at an another country and these days i have exams and i couldnt contact my proffessor to ask him.
    Again thank you.
    Stupid question: Are you working in C?

    Second stupid question: What version of C?

    I've been working professionally in C and C++ since circa 1990. Around 1998 or 1999, a new standard came out for C++. I completely missed it, but it showed up on this forum and many seem to be using it.

    The ANSI C standard came out in 1989, so that's sometimes referred to as C89. In 1999, a new C standard emerged which largely incorporated features of C++. That standard appears to be largely academic, as is the 2011 standard, C11. For example, Microsoft Visual Studio supports neither C99 not C11, since they have dedicated themselves to C++ instead of C. In my own professional experience (from circa 1990), I have yet to see another professional use anything beyond C89.

    But in your school, what version of C are you using?

    Interestingly, if you are in the Third World and using Turbo C, then it might even be questionable whether you're using C89. But that standard, AKA "ANSI C", should be a good starting point. I have Schildt's annotated publication of the C89 standard at work. I can forward the standard designation to you then, a bit more than six hours from now.


    My own start was in USAF tech school as an electronic computer systems repairman. We started with the basic binary electronics and proceeded from there. Two's Complement was drilled into us from the beginning. At the local university where I pursued my Computer Science degree, we dealt with hexadecimal printouts, but they always taught us to convert from hex to binary (easily doable by sight, hence the prevalence of hex and octal), perform the Two's Complement, then convert back from binary to hex (again, easily doable by sight). I very quickly realized that I could just do 15's and 16's Complement instead. Think about it; figure it out.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    10
    Rep Power
    0
    I study in a university in greece Google "csd auth".
    Also yeah in this first semester we work on c and so do i.
    Now about the version of c we use is c(99) but because we are still on basics c(89) works for us too.For example i use Bloodshed Dev-C++ and i write in c(89) but i know it can easily be changed to c(99) when i want.But at last our primary goal on this course is to learn basic programming principles and structured programming.
  18. #10
  19. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,151
    Rep Power
    2222
    Errrr....

    BloodShed Dev-C++ has not been supported for many years now.

    The actual compiler it uses is MinGW gcc, a port of the Linux GNU cc compiler. I completely gave up on Dev-C++, since when trying to do Petzold-style Windows programming the necessary compile/build icons absolutely refused to become enabled. However, from the command line I continued to use the gcc port, though it relies on a Microsoft run-time library which, in later Windows versions, could result in version problems.

    C89 is much more restrictive than C99 is. Especially in the issue of allowing date declarations intermixed with executable lines of code; C++ and C99 allow it, but C89 does not.

    But for learning basic programming and structured programming, either will suffice. But please, when you post code, let us know which version of C you are using. We professionals tend to overlook C99.
  20. #11
  21. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,381
    Rep Power
    1871
    Draft C99
    This is the last public DRAFT of C99.
    Whilst it isn't the actual C99 standard, it does have the advantage of being free.

    For sure, any substantial change would have resulted in another draft (and more talking in the committee), so it's reasonable to assume that any differences are either cosmetic, or of interest only to writers of compilers and compiler test suites.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    10
    Rep Power
    0
    We still are at a basic level.
    I know(better say (i think)) that things like

    Code:
    for(int i=0;i<10;i++)
    are not allowed in c(89).

    But i heard that with -std=c99 i can do this (i talk about bloodshed dev now)

    To tell you the truth i am not really familiar with all these things like all those different compilers and versions of C YET.Because as i said our target is to learn other things right now.

IMN logo majestic logo threadwatch logo seochat tools logo