Issue
I got a lot of memory pieces in 512 bits. I need to write numbers in 20 bits.
For example:
// a piece of 512 bits memory
void *p = malloc(64);
struct Coords {
int20_t x, y;
};
// usage
Coords *pcoord = (Coords *)p;
for (int i = 0; i < 512 / 40/*sizeof(Coords)*/; ++i) {
pcoord[i].x = i;
pcoord[i].y = 2 * i;
}
How to implement int20_t ?
I need exactly 20 bits for an integer. The numbers must be continuous. ( [0] to [19] for the first Coords.x; [20] to [39] for the first Coords.y; ... There are 12 pairs of Coords with 480 bits and 32 bits for the pad.)
Solution
The type int20_t
is only available on very specific hardware with 20 bit registers. You do not need this type to handle your data, you can either use plain int
to store the coordinates or possibly use bit-fields but it does not seems necessary.
The main issue is the conversion from the external representation (12 packed pairs of 20 bit values in a 512 bit block) to a more manageable in memory representation as an array of structures, and possibly the other way around.
To handle this conversion, you must specify precisely how the bits are packed in the 64 byte block. Each value will be split in 3 parts, the order of these bytes and bits inside the last byte bytes must be specified.
Here is an example where values are stored in big endian format with the third byte containing the low order bits of x
in its high order bits and the high order bits of y
in its low order bits:
struct Coords {
int x, y;
};
void load_coords(struct Coords *a, const unsigned char *p) {
for (int i = 0; i < 20; i++) {
a->x = (p[0] << 12) + (p[1] << 4) + (p[2] >> 4);
a->y = ((p[2] & 15) << 16) + (p[3] << 8) + p[4];
p += 5;
a++;
}
}
void store_coords(unsigned char *p, const struct Coords *a) {
for (int i = 0; i < 20; i++) {
p[0] = a->x >> 12;
p[1] = a->x >> 4;
p[2] = (a->x << 4) | ((a->y >> 16) & 15);
p[3] = a->y >> 8;
p[4] = a->y;
p += 5;
a++;
}
}
Answered By - chqrlie Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.