简体   繁体   中英

Determining number size in c++

I am given the hex number 0x04030201 , stored in the middle of an array filled with zeroes. My code has to determine the size of this number in bits .

I am required to implement this in 2 different ways. My first way was to use the sizeof() function like this:

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int num[] = {0,0,0x04030201,0,0};

    cout<<"The size of the integer is "<<sizeof(num[2])*4<<" bits."<<endl;

    return 0;
}

My expected output is 28 bits(4 bits times the 7 significant characters). But my output gives:

The size of the integer is 16 bits.

What's my mistake?

What's my mistake?

Using the wrong tool.

If you look up sizeof in your favourite documentation, you'll see that it tells you how many bytes an object or type takes up. This has nothing to do with counting the number of significant bits in an integer value , and I don't know whence you got the notion that it would.

If you want to count significant bits in an integer, you will need either of:

  1. A numerical algorithm to calculate this using bitwise arithmetic, or
  2. A compiler intrinsic to do this for you, eg __builtin_clz in GCC (subtracted from total number of bits in the type — now you can use sizeof !)

My code has to determine the size of this number in bits

What does that mean?

Is it:

  1. the size of the smallest type native to your (unspecified) architecture which can represent your number?

    in this case, your code

     sizeof(num[2])*4 

    is wrong because it (for some reason) assumes 4-bit chars. If you want to know the number of bits in a char, it's called CHAR_BIT . The sizeof expression correctly gives you the size in chars, so the code should be

     sizeof(num[2])*CHAR_BIT 

    Note however that sizeof(num[2])==sizeof(num[0])==sizeof(int) , because every int is the same size: it doesn't depend on what value it holds.

  2. Or did you want the smallest number of bits that can represent your number, ignoring what those bits are stored in?

    In this case log 2 (n) gives you the power of 2 your number represents. Taking the floor of that (truncating the floating-point value to an integer) gives you the number of the highest bit. Add one to get the number of bits (they start from zero, since you need one bit to represent 1=2 0 ).

    If you want to do this without using logarithms, start by writing out your number in base 2 (start with a smaller number for testing, to save time). Hint: examine what happens when you divide it by 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM