c언어 문자열로 받은 16진수 그대로 주소값으로사용하기

s7mile의 이미지

char test[20] = "0x123456";
int* a;
 
sscanf(test, "%x", &a);

위의 코드처럼 작성했는데요
sscanf를 한 후 a의 주소값을 출력하였을 때
0x 7fff 123456
이런식으로 중간에 7fff가 들어가집니다
해결방법이 있을까요?

HDNua의 이미지

len = strlen(test);
int mask = -1; // 11111111
mask <<= len; // 11000000
mask = ~mask; // 00111111
a &= mask;

딱 떠오른 방법인데 이런 건 어떤가요? 성능은 썩 좋아보이지는 않긴 한데.

저는 이렇게 생각했습니다.

HDNua의 이미지

C를 이용한 구현입니다.

#include <stdio.h>
#pragma warning(disable:4996)
 
int main(void) {
    char test[20] = "0x7f123456";
    int* a;
    int len;
    int mask;
 
    // get pointer value from string first
    sscanf(test, "%x", &a);
    printf("before\t: %016p \n", a);
 
    // make got pointer value valid
    len = 6;
    mask = ~(-1 << (len * 4)); // 4 bit for 1 digit
    a = (int *)((int)a & mask);
    printf("after\t: %016p \n", a);
 
    return 0;
}

저는 이렇게 생각했습니다.

shint의 이미지

DevC++ 5.11 (.CPP 파일)
WindowsXP 32비트 (서비스팩 없는 버전)

질문하신분 소스 그대로 해도. 123456 그냥 나옵니다.

//----------------------------
아래 소스코드는 웹 컴파일러에서 확인한 경우입니다.
http://www.codepad.org/
C로 하면. 그냥 되고.
C++로 하면. 이와 같은 오류 메시지가 발생합니다.

#include <stdio.h>
 
cc1plus: warnings being treated as errors
In function 'int main(int, char**)':
Line 12: warning: format '%x' expects type 'unsigned int*', but argument 3 has type 'int**'
Line 13: warning: format '%x' expects type 'unsigned int', but argument 2 has type 'int*'
 
//C에서는 컴파일이 성공하고. C++에서는 오류가 발생한 경우
int main(int argc, char** argv) 
{
 
    char test[20] = "0x123456";
    int* a;
 
    sscanf(test, "%x", &a);
    printf("%x\n", a);
 
    return 0;
}
 
 
 
#include <stdio.h>
 
//int 형 변수로 성공한 경우
int main(int argc, char** argv) 
{
 
    char test[20] = "0x123456";
    unsigned int a;
 
    sscanf(test, "%x", &a);
    printf("%x\n", a);
 
    return 0;
}
 
 
#include <stdio.h>
 
//new 로 할당해서 성공한 경우
int main(int argc, char** argv) 
{
 
    char test[20] = "0x123456";
    unsigned int* a = NULL;
    a = new unsigned  int[1];
 
    sscanf(test, "%x", a);
    printf("%x\n", *a);
    delete a;
 
    return 0;
}

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

jick의 이미지

64비트 머신 기준으로 포인터는 8바이트이고 unsigned int는 4바이트인데 sscanf에서 %x (unsigned int) 를 사용했으니 4바이트만 공간을 채워주고 나머지는 쓰레기값이 들어가겠죠. 컴파일해 보니 gcc는 다음과 같이 경고를 내주네요.

$ cat x.c
#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char test[] = "0x123456";
    int *a;
    sscanf(test, "%x", &a);
    return 0;
}
 
$ gcc -W -Wall x.c
x.c: In function ‘main’:
x.c:8:5: warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘int **’ [-Wformat=]
     sscanf(test, "%x", &a);
     ^

경고는 에러라고 생각하고 -W -Wall 켜고 다 잡는 게 좋습니다.

%x 대신 %p를 써보세요. (이게 표준으로 보장이 되는지는 잘 모르겠습니다만 적어도 linux gcc에서는 되는 것 같군요.)

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.