Domanda

I am going through a book and one of the question it asks.

Write a program that shows you how much memory a float consumes. On your Mac, a short is a 2-byte integer, and one bit is used to hold the sign (positive or negative). what is the smallest number it can store? What is the largest? An unsigned short only holds non-negative numbers. What is the largest number it can store?

So i get the first part about how much memory a float consumes but i do not get how to find the smallest or largest number. can someone explain?

Thanks in Advance S.

È stato utile?

Soluzione

Lets forget about short or unsigned short. Lets say you have 1 byte which is 8 bits. What is the maximum number it can present? Every bit has two states 0 or 1. So 8 bits has 28 number of combinations. Which is 256. Now we have a 0 value so its 0 to 255, total 256 numbers. Now back to your original question,

You have 2 bytes which means 2*8=16 bits. For signed short a bit is consumed by the sign bit. So you have 15 bits total. Which means 215 = 32768 total combinations. But your sign bit also have 2 states. 0 and 1. For positive number its 0 to 32767 and for negative its -32768 to 0. So signed short can hold values ranged -32768 to 32767. Now for unsigned short there is no sign bit. So all the 16 bits are usable. So you have 216 = 65536 combinations. The values ranged from 0 to 65535, total 65536 numbers.

Also read the answer in this thread to have clear idea why its range 32767 in the positive but -32768 in the negative.

Altri suggerimenti

#include <stdio.h>
#include <limits.h>

int main(){
    printf("how much memory a float consumes?\n");
    printf("%d byte\n", (int)sizeof(float));//%zu
    printf("what is the smallest number of short?\n");
    printf("%hd\n", SHRT_MIN);
    printf("What is the largest?\n");
    printf("%hd\n", SHRT_MAX);
    printf("What is the largest number of unsigned short?\n");
    printf("%hu\n", USHRT_MAX);

    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top