2017-01-06 2 views
1

간단히 말해서, 제 문제는 다음과 같습니다. 다양한 종류의 객체가 포함 된 동적 메모리 관리자를 만들고 있습니다. 서로 다른 종류의 객체를 태그로 표시하고 메모리 디버깅을 쉽게하기 위해이 태그를 읽을 수있는 4 바이트 문자열로 메모리에 표시하려고합니다. 그러나 이러한 값을 효율적으로 전환하려면 부호없는 32 비트 정수로 간주해야합니다.4 바이트 문자열의 값을 하나의 단위로 가져 오기

현재 객체의 정의는 다음과 같습니다

#define CONSTAG "CONS" 

내가 할 수 원하는 것은 너무

같은 것입니다 TO :

/** 
* 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; 
}; 

태그 예를 들어, 네 개의 문자열 상수

switch (cell.tag) { 
    case CONSTAG : dosomethingwithacons(cell); 
    break; 

물론 문자열을 전환 할 수는 없습니다. 그러나 4 바이트 문자열이므로 32 비트 부호없는 정수로 메모리에서 읽을 수 있습니다. 내가 원하는 건 문자열을 인자로 받으면 unsigned int를 반환하는 매크로이다. 나는

/** 
* a macro to convert a tag into a number 
*/ 
#define tag2uint(tag) ((uint32_t)*tag) 

하지만를 시도했다가 실제로 그 주소에서 숫자로 첫 번째 문자의 ASCII 값을 반환입니다 않는다 -, 즉 '의 아스키 코드입니다

tag2uint("FREE") => 70 

에프'.

누구나 나를 해결할 수 있습니까? 내가 C.에

답변

2
#define tag2uint(tag) ((uint32_t)*tag) 

수단을 심각한 아무것도 쓴 이후로는 이십년이다 "tag (귀하의 예제에서 'F'를 얻을 수), 다음 uint32_t로 변환 역 참조." 이 의미

#define tag2uint(tag) (*(uint32_t*)tag) 

해야 수행 할 작업을

"다음 역 참조, uint32_t에 포인터로 tag을 취급합니다."

관련 문제