Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a 1 bit flag in a 64 bit pointer

Tags:

c++

If you define a union for traversing a data structure squentially (start and end offset) or via a pointer to a tree structure depending on the number of data elements on a 64 bit system where these unions are aligned with cache lines, is there a possibility of both adding a one bit flag at one of those 64 bits in order to know which traversal must be used and still allowing to reconstruct the right pointer?

union {
    uint32_t offsets[2];
    Tree<NodeData> * tree;
};
like image 919
Matthias Avatar asked Nov 26 '25 03:11

Matthias


1 Answers

It's system dependent, but I don't think any 64-bit system really uses its full pointer-length yet.
Also, if you know your data is 2n-aligned, chances are those n bits are just sitting idle there (On some old systems they just would not exist. But I don't think any of those were 64-bit systems, and anyway they are no longer of interest).

As an example, x86_64 uses 48bits, the upper 16 must be the same as bit47. (sign-extended)
Another example, ARM64 uses 49bits (2 mappings of 48bit at the same time), so there you only have 15 bits left.

Just remember to corect the pilfered bits. (You might want to use uintptr_t instead of a pointer, and convert after the correction.)

Using a mis-aligned or impossible pointer causes behavior ranging from silent auto-correction, ranging over silent mis-behavior, to loud crashes.

like image 95
Deduplicator Avatar answered Nov 27 '25 16:11

Deduplicator