Binary and DataType

Here are the binary values for the address in memory for an integer and a double..
Can you tell what dataType they are by reading the binary address?
Is there somewhere in binary that says this is a 4 byte long dataType
and a double is 8 bytes long?
00000000011111111111111101011111101111111111100110101100
00000000011111111111111101011111101111111111010100100000
Can someone please elaborate..
Last edited on
No. You cannot say that by single address.
If you have addresses of 2 consecutive elements of the array, you can find out size of underlying type by finding difference between addresses.
> Can you tell what dataType they are by reading the binary address?

No. But you can tell what data type they can't be.

Types have alignment requirements which place restrictions on the addresses at which an object of that type may be placed. If an address does not meet the alignment requirements of double, then the object at that address can't be a double.
http://coliru.stacked-crooked.com/a/9bd0a40a58c20822
JLBorges: But couldn't I say
1
2
3
4
5
6
double x = 3.141592;
char mem[100];
uintptr_t p = (uintptr_t)mem;
p = p + (p&~(uintptr_t)7) + 17;
double *y = (double *)p;
*y = x;
?
Last edited on
You could.
And unless it is one of your especially unlucky days, your program would crash instantly.
http://coliru.stacked-crooked.com/a/c30bef83d0448e2c

In contrast, this may work, with no surprises, on certain platforms under certain conditions.
For example on the Intel family of processors, which tolerates (albeit with substantial performance penalty) access to misaligned data, and assuming that strict-aliasing rules do not enter the picture (as it does not in this 12 line snippet).

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    double x = 3.141592;
    char mem[100];
    std::uintptr_t p = (uintptr_t)mem;
    p = p + 17;
    double *y = (double *)p;
    *y = x;
    std::cout << *y << '\n' ;
}

http://coliru.stacked-crooked.com/a/a2d4b80146d2897a
Whoops. I meant to say p = (p&~(uintptr_t)7) + 17;

But anyway, yes, a double can sometimes exist at any memory position. You can't really say that something is not a double if all you have is an address.
> But anyway, yes, a double can sometimes exist at any memory position
> You can't really say that something is not a double if all you have is an address.

I agree completely. All that is required is to remove C++ from the discussion. Then the double being talked about would not be the type double as defined by the IS.

Object types have alignment requirements which place restrictions on the addresses at which an object of that type may be allocated. ...
An object type imposes an alignment requirement on every object of that type; ...

Mere C++ noise - totally irrelevant if we are not talking about C++.
Topic archived. No new replies allowed.