[英]Getting the value of a C 4-byte string as a uint
簡而言之,我的問題是:我正在構建一個動態內存管理器,其中包含各種不同類型的對象。 我正在用標記標記每種不同的對象,並且為了使內存調試更容易,我希望這些標記以四字節字符串的形式顯示在內存中,這些字符串可以讀取。 但是,為了有效地打開這些值,我還想將它們視為無符號的32位整數。
當前,對象的定義如下所示:
/**
* an object in cons space.
*/
struct cons_space_object {
char tag[TAGLENGTH]; /* the tag (type) of this cell */
uint32_t count; /* the count of the number of references to this cell */
struct cons_pointer access; /* cons pointer to the access control list of this cell */
union {
/* if tag == CONSTAG */
struct cons_payload cons;
/* if tag == FREETAG */
struct free_payload free;
/* if tag == INTEGERTAG */
struct integer_payload integer;
/* if tag == NILTAG; we'll treat the special cell NIL as just a cons */
struct cons_payload nil;
/* if tag == REALTAG */
struct real_payload real;
/* if tag == STRINGTAG */
struct string_payload string;
/* if tag == TRUETAG; we'll treat the special cell T as just a cons */
struct cons_payload t;
} payload;
};
標簽是四個字符串常量,例如:
#define CONSTAG "CONS"
我想要的是這樣的
switch ( cell.tag) {
case CONSTAG : dosomethingwithacons( cell);
break;
但是,當然不能打開字符串。 但是,由於它們是四個字節的字符串,因此可以將它們作為32位無符號整數在內存中讀取。 我想要的是一個宏,給定一個字符串作為參數,它返回一個無符號的整數。 我試過了
/**
* a macro to convert a tag into a number
*/
#define tag2uint(tag) ((uint32_t)*tag)
但實際上它所做的是返回該地址第一個字符的ASCII值作為數字-即,
tag2uint("FREE") => 70
這是“ F”的ASCII碼。
有人為我解決嗎? 自從我用C編寫任何嚴肅的書以來已經有20年了。
#define tag2uint(tag) ((uint32_t)*tag)
表示“取消引用tag
(在示例中為'F'
,然后將其轉換為uint32_t
。
你想做的應該是
#define tag2uint(tag) (*(uint32_t*)tag)
這意味着“將tag
作為指向uint32_t
指針,然后對其取消引用”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.