Challenge 2 - Why use a program


#1

Why is everyone putting up programs to solve this.

2 bytes contain 2 x 8 = 16 bits. This can store 2 to the power of 16 pieces of information = 65536. With the signed short, one bit is used for the sign, one for zero, so 65534 are left for other numbers. 65536 divided by 2 is 32767. The smallest number that can be stored is -32767, the largest +32767

With the unsigned short, one bit is used for zero, so 65536 - 1 are left of other numbers. The largest number that can be stored is 65535

Am I missing something?


#2

That is not quite right. You should have written a program to verify your reasoning.

// main.m

int main (int argc, const char * argv[])
{
    // Smallest and largest signed short value
    typedef short value_type;
    value_type smallest = (value_type)0x8000;
    value_type largest  = (value_type)0x7FFF;
    printf ("signed short: [%d, %d]", smallest, largest);
    
    {
        // Smallest and largest unsigned short value
        typedef unsigned short value_type;
        value_type smallest = (value_type)0x0000;
        value_type largest  = (value_type)0xFFFF;
        printf (" unsigned short: [%d, %d]\n", smallest, largest);
    }
    return 0;
}
signed short: [-32768, 32767] unsigned short: [0, 65535]

[Become a competent programmer faster than you can imagine: pretty-function.org]


#3

Hi ibex10

I started to go through your example and right away I noticed that you imported Foundation.

I am under the impression that Foundation is just for Objective C and we are all at a C level here.

Why did you do this?

[color=#000040]JR[/color]


#4

Propagation due to copy and paste. You are right there is no need to import it. I will fix it.


#5

He wants you to write a program so you’ll continue to use the math library. Given his setup in the question, this pretty much works out to obtaining the power of some number, in which you might go hunting in the docs for the pow function.

[code]#include <stdio.h>
#include <math.h>

int main(int argc, const char * argv[]) {
printf(“The smallest number a short can store is %.0f\n”, -pow(2,15));
printf(“The largest number a short can store is %.0f\n”, pow(2,15)-1); // subtract 1 because of zero
printf(“The largest number an unsigned short can store is %.0f\n”, pow(2,16)-1); // subtract 1 because of zero
return 0;
}
[/code]


#6

But the problem is, we haven’t been taught these math functions so far in the book.

I understand them now, but without reading this forum I would have had no idea how to do this other than by hand.