unsigned char -> unsigned short 캐스팅에 궁금한 점이 있습니다.

atdty의 이미지

unsigned short B;
unsigned char A[2];

B = 42344;

memset(A, 0x00, sizeof(A));
memcpy(A,(char*)&B+1,1);
memcpy(A+1,(char*)&B,1);

unsigned short result;

result = *(unsigned short *)(A+2);

1. 이렇게 했을 때 값이 제대로 나오는데 왜 1바이트차이나는데 +2이며,
2. unsigned short->unsigned char 로 쉬프트연산을 하는 방법을 알고싶습니다..

klara의 이미지

어떤 값이 제대로된 값인지, unsigned short->unsigned char로 쉬프트 연산이 무엇인지를 먼저 정의해주세요.

atdty의 이미지

b를 출력 하는 것입니다. unsigned char로 변환후 unsigned short으로 다시 변환하는 과정을

나타낸 소스입니다.

그러니까.. unsigned char ??[] 에서 unsigned short으로 변환하는 과정이 궁금합니다..

익명 사용자의 이미지

시스템에 따라 다르지만 x86 머신이면 리틀 엔디안일테고, 위의 값 42344를 16진수로 변환하여 메모리 공간에 어떻게 저장되는지 그려보세요.

cats96의 이미지

unsigned short B;
unsigned char A[2];
unsigned short result;

B = 42344;

memset(A, 0x00, sizeof(A));
memcpy(A,(char*)&B,2);

result = *(unsigned short*)(A);

printf("result = %d\n",result);

위와같이 짰을때 별문제없이 출력이 되네요
short형태의 addr +1은 2byte의 영역입니다
short형태의 addr +1이 두번째바이트영역을 가리키진 않습니다 다른 어드레스영역을 가리키죠
그러므로 char -> short -> char로의 타입캐스팅은 위와같이 해야할듯하네요

익명 사용자의 이미지

result = *(unsigned short *)(A+2);

잘못된 코드입니다. 그럼에도 위의 코드가 올바로 동작하는 이유는 '우연하게도' B가 A+2 의 위치에 존재하기 때문입니다.
(물론 그렇게 동작하는데에는 나름 이유가 있습니다. 함수 내의 지역변수가 스택 내에 할당되는 방식과 관련이 있는데, 유감스럽게도 프로그래머가 신뢰하고 의존할만한 동작이 절대 아닙니다)

그리고 A타입으로 선언된 메모리 공간을 캐스팅 연산자와 참조 연산자를 이용해서 B타입인 것처럼 사용하는 방식은 되도록 피해야 할 방식입니다.
잘못된 메모리 참조 문제를 마주하기가 쉬우며,
상황에 따라서는 메모리 정렬제한 문제를 겪을 수 있습니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.