tags:

views:

88

answers:

3

I'm pretty sure i'm the one who's just dumb and don't know my data structures...

None the less, i'm going to post it here for you brilliant guys, so one of you may explain to me why this doesn't work:

#include <iostream>
using namespace std;

double data_convert(int n);

int main(void) {
    cout << data_convert(sizeof(int));
}

double data_convert(int n) {
    int i;
    double x;

    x = 8 * n;
    for(i = 0; i < 32; i++)
        x = x * 32;
    return x;
}

I tried using pow from cmath, but I got the same results. Apparently, this outputs "4.67681e+049". Where as it should output (using Windows Calculator) "4294967296".

The for loop is my own hardcoded pow() function for this specific task. All I wanna do is make a program that can show how big a data type is, along with it's range (bit range or something, yeah?)

Thank you.

+6  A: 

If you want 2^32, you should be multiplying by 2 each time. Your code multiplies by 32 each time, so you'll end up with a much larger value.

Also, your x value should start from 1. 8 * n is actually the number of bits in the integer, so that should be your upper limit for the loop:

x = 1;
for (i = 0; i < 8 * n; i++)
  x = x * 2;
return x;

A simpler method would be to bitwise negate 0, which will give you the largest possible integer:

return ~0;

will give you 2^32 - 1 = 4294967295 (on a 32-bit machine).

casablanca
And adding casting to whatever integer datatype that needs testing should work I suppose.
Matthew Mitchell
Nice, no wonder I failed math in high school. Thank you very much
Christopher
`~0` is wrong. First you suppose that your integers are represented in two's complement, which they mustn't. And even then, the number the OP is looking for is just not representable as an `int` but only as an `unsigned int`. `(unsigned)-1` would have been the answer that always works. In two's complement the number you have given would be (int)-1.
Jens Gustedt
@Jens Gustedt: Agreed, I never gave a thought about a non-two's complement computer. :)
casablanca
A: 

I'm not sure what you're doing, but don't you meanx = x*2?

Conor
+1  A: 

Basically you are multiplying the input by 8 and are then multiplying that by 32, 32 times.

I don't understand what that is suppose to get you to.

If you want the range of an unsigned integer for x amount of bytes you should use this calculation:

max number = 2^(bytes*8) - 1

So in the loop it should multiply 2 until i goes from 0 to bytes*8 and stop there (So it ends before it gets to bytes*8)

Matthew Mitchell