programing

redistrepect_cast의 C에 해당하는 것은 무엇입니까?

iphone6s 2023. 7. 6. 21:58
반응형

redistrepect_cast의 C에 해당하는 것은 무엇입니까?

의 C 등가물은 무엇입니까?reinterpret_castC++에서?

int *foo;
float *bar;

// c++ style:
foo = reinterpret_cast< int * >(bar);

// c style:
foo = (int *)(bar);

값의 주소를 가져올 수 있는 경우 한 가지 방법은 값에 대한 포인터를 다른 유형에 대한 포인터로 캐스트한 다음 포인터의 참조를 해제하는 것입니다.

예를 들어, float-to-int 변환은 다음과 같습니다.

int main()
{
  float f = 1.0f;

  printf ("f is %f\n", f);
  printf ("(int) f is %d\n", (int)f);
  printf ("f as an unsigned int:%x\n", *(unsigned int *)&f);
}

출력:

f is 1.000000
(int) f is 1
f as an unsigned int:3f800000

이것은 아마도 C 표준에 의해 작동하는 것을 보장하지 않을 것입니다.deslate_cast를 사용하여 float에서 int로 캐스트할 수는 없지만 지원되는 유형(예: 서로 다른 포인터 유형 간)에 대해서는 유사합니다.

어쨌든 위의 출력이 타당한지 확인해 보겠습니다.

http://en.wikipedia.org/wiki/Single_precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32

이진법으로 표시된 마지막 답변:

0011 1111 1000 0000 0000 0000 0000 0000

이것은 IEEE-754 부동소수점 형식입니다. 부호 비트 0, 8비트 지수(0111111), 23비트 가수(모두 0)입니다.

지수를 해석하려면 127: 011111b = 127, 127 - 127 = 0을 뺍니다.지수는 0입니다.

가수를 해석하려면 1 뒤에 소수점 1.0000000000000000000(23개의 0)을 입력합니다.이것은 십진수로 1입니다.

따라서 16진수 3f800000으로 표시되는 값은 예상한 대로 1 * 2^0 = 1입니다.

C 스타일 캐스트는 괄호 안의 유형 이름과 같습니다.

void *p = NULL;
int i = (int)p; // now i is most likely 0

분명히 이것보다 깁스를 더 잘 사용하는 것이 있습니다. 하지만 그것이 기본적인 구문입니다.

존재하지 않는 이유는reinterpret_cast[일관성][3]을 변경할 수 없습니다.예를들면,

int main()
{
    const unsigned int d = 5;
    int *g=reinterpret_cast< int* >( &d );
    (void)g;
}

다음 오류가 발생합니다.

dk.cpp: 'int main()' 함수:
dk.cpp:5:41: 오류: 'const unsigned int*' 유형에서 'int*' 유형으로 redistrepect_cast를 제거합니다.

C 스타일 캐스트는 다음과 같습니다.

int* two = ...;
pointerToOne* one = (pointerToOne*)two;

A는 어떻습니까?REINTERPRETc에 대한 연산자:

#define REINTERPRET(new_type, var) ( * ( (new_type *)   & var ) )

저는 "reinterpret_cast"라고 말하는 것을 좋아하지 않습니다. 왜냐하면 캐스트는 변환(단위: c)을 의미하는 반면, 재해석은 그 반대를 의미하기 때문입니다.

다른 유형과 마찬가지로 C에서 포인터 유형을 자유롭게 캐스트할 수 있습니다.

완료하기:

void *foo;
some_custom_t *bar;
other_custom_t *baz;
/* Initialization... */
foo = (void *)bar;
bar = (some_custom_t *)baz;
baz = (other_custom_t *)foo;

언급URL : https://stackoverflow.com/questions/1382051/what-is-the-c-equivalent-for-reinterpret-cast

반응형