我有很多 512 位的記憶體片段。我需要用 20 位寫數字。
例如:
// 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;
}
如何實作int20_t?
我需要一個整數正好 20 位。數字必須是連續的。 (第一個 Coords.x 為 [0] 到 [19];第一個 Coords.y 為 [20] 到 [39];... 有 12 對 Coords,480 位和 32 位用于填充。)
uj5u.com熱心網友回復:
該型別int20_t僅在具有 20 位暫存器的特定硬體上可用。您不需要這種型別來處理您的資料,您可以使用 plainint來存盤坐標或可能使用位域,但似乎沒有必要。
主要問題是從外部表示(512 位塊中的 12 對 20 位值的打包對)轉換為更易于管理的記憶體表示作為結構陣列,可能反過來。
要處理此轉換,您必須準確指定位在 64 位元組塊中的打包方式。每個值將分為 3 部分,必須指定這些位元組的順序和最后一個位元組位元組內的位。
這是一個示例,其中值以大端格式存盤,第三個位元組包含x其高位的低位和低位的y高位:
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 ;
}
}
uj5u.com熱心網友回復:
你不能。在int20_t x, y;中,您需要小數對齊(除非您有 10 位硬體)。
理由是它&y必須是一個int20_t*,可轉換為void*。
您可以為整個 480 位創建一個包裝器型別,使用operator[].
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425954.html
下一篇:與C 11函式簽名不一致
