sizeof and how many bytes

Hello, I tried to do some experiment. The result are different and confused. Could anybody explain what and where do each line do. I saw the max number before it become overflow, I wanted to have it show the max before break. Then this happened, different from what I expected.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdint>

int main()
{
    int16_t i(32767); // able to hold 32,767 byte.

    std::cout << sizeof(int) << std::endl; // how do I type in in order to count how much i(32767) in bytes? for this line 4 is what it made in run

    std::cout << i; // somehow this show 32767~ what does this mean? and how did it happen?

    int8_t x(126); // able to hold 126 byte

    std::cout << x; // fail, show nothing why? there are no return until line 15. could this be because of the { } ? 
    return 0;
}

// The result I get are
// 4
// 32767~

// I'm confused how it work.
Last edited on
closed account (SECMoG1T)
hello the code you have works as expected, let me correct you on some statements though.

1
2
int16_t  ///can hold a max of 2 bytes.
int8_t   /// can hold 1 byte, one byte is 8 bits. 


sizeof(int) == 4;
the value of i-> is within 2 bytes and == 32767 show by cout<<i;

the value of x == ~;
here you need to realize that int8_t and char are the same thing one byte in size so

1
2
3
4
5
int8_t x(126);
char    y(126);

std::cout<<x<<"  "<<y<<std::endl;
///will show the same thing. 
Last edited on
32,767
look closer :) 32768 (because zero... it took one of the bit positions to represent zero, so this is how many "values" it can hold, 0-32767 is 32768 possible values).

anyway 32768 is... 2 to the 15th power. if you had used an unsigned int, it would have been 2 to the 16th power -1, 65535. Try it again with unsigned and put that value in it :)

you can find out how big the number can be by 2 to the number of bits, then, or find out what a number needs to be stores with lg (that's log base 2 symbol) of the number: lg 65536 is 16 …

does that help?

one more thing: what is the ascii lookup value of ~?
why, it appears to be... 126! you are printing a character, and that char happens to be 126, that is where the ~ came from and why it printed "nothing" in your mind when you expected a value. do this
char x = '~';
cout << (int)x << endl;

the most significant bit of a signed value is sometimes called the sign bit, but negative numbers are a little more complex than that. they use a neat property of binary --- flip the bits and add 1, and that is the negative value.
for example, for a byte, 00001111 is 15. minus 15, then is 11110001, try it in windows calc in programmer mode in binary. now add them together...
1
2
3
4
5
 
 00001111 
 11110001
100000000  //but the 1 on the far end is discarded and its zero.  


Last edited on
ohh now I got it, thanks!
Topic archived. No new replies allowed.