C언어 구조체 변수 비교 방법

kkb의 이미지

struct example {
    unsigned char a : 1;
    unsigned char b : 1;
    unsigned char c : 1;
    unsigned char d : 1;
    unsigned char e : 1;
    unsigned char f : 1;
    unsigned char g : 1;
    unsigned char h : 1;
};
 
struct example ex1;
struct example ex2;

ex1과 ex2값이 같은지 다른지 한번에 비교할 수 있을까요?

라스코니의 이미지

1) XOR을 쓰거나
if(!(ex1 ^ ex2)) ex1과 ex2가 같으면 XOR한 값이 0, 그래서 !(0)은 TRUE로 판정됩니다.

2) casting 해서 비교
if((unsigned char)(ex1) == (unsigned char)(ex2))

익명 사용자의 이미지

테스트는 해 보고 올리신 거죠...?

라스코니의 이미지

테스트해 보지 않고 적었는데 간단히 되지는 않는군요.

아래는 한 예입니다. 단 아랫분이 언급한 것처럼 side-effect가 있을수는 있습니다.

#include <stdio.h>
struct example {
    unsigned char a : 1;
    unsigned char b : 1;
    unsigned char c : 1;
    unsigned char d : 1;
    unsigned char e : 1;
    unsigned char f : 1;
    unsigned char g : 1;
    unsigned char h : 1;
};
 
struct example ex1 = {1, 1, 1, 1, 1, 1, 1, 1};
struct example ex2 = {1, 1, 1, 1, 1, 1, 1, 1};
 
int main()
{
    if(!(*(unsigned char *)&ex1 ^ *(unsigned char *)&ex2))
        printf("Identical!\n");
    else
        printf("Not same.\n");
 
    if(*(unsigned char *)&ex1 == *(unsigned char *)&ex2)
        printf("Identical!\n");
    else
        printf("Not same.\n");
 
    return 0;
}
익명 사용자의 이미지

1. 단순 노가다

_Bool comparing_example(struct example ex1, struct example ex2){
	return (
		(ex1.a == ex2.a) &&
		(ex1.b == ex2.b) &&
		(ex1.c == ex2.c) &&
		(ex1.d == ex2.d) &&
		(ex1.e == ex2.e) &&
		(ex1.f == ex2.f) &&
		(ex1.g == ex2.g) &&
		(ex1.h == ex2.h)
	);
}

한 번만 함수로 만들어 놓으면 됩니다.
C++였으면 bool operator==(const example &ex1, const example &ex2); 했겠죠.

2. 라이브러리 의존

memcmp(&ex1, &ex2, sizeof(struct example))

깔끔하고 좋긴 한데, 결과적으로 1바이트 비교하려고 라이브러리 함수를 호출하는 것이죠.

3. 막가파식 방법 (비추)

ex1ex2가 모두 lvalue이고,
struct example이 정확히 1바이트일 것이라고 확신할 수 있다면...

(*(unsigned char *)&ex1) == (*(unsigned char *)&ex2)

간편하긴 하고 실제로 이런 테크닉 여러 군데서 종종 봅니다만 권장할 만한 일인지는 잘 모르겠네요.

나빌레라의 이미지

union ex {
	unsigned char ch;
 
	struct example {
	    unsigned char a : 1;
	    unsigned char b : 1;
	    unsigned char c : 1;
	    unsigned char d : 1;
	    unsigned char e : 1;
	    unsigned char f : 1;
	    unsigned char g : 1;
	    unsigned char h : 1;
	} bit;
};
 
union ex a;
union ex b;
 
a.bit.a = 1;
a.bit.e = 1;
 
b.bit.a = 1;
b.bit.e = 1;
 
printf("same? %d\n", a.ch == b.ch);

테스트는 안해봤습니다.

----------------------
얇은 사 하이얀 고깔은 고이 접어서 나빌레라

swish95의 이미지

비트 쪼개기..ㅋㅋ

------------------------------------------------------------
ProgrammingHolic

서지훈의 이미지

#include <stdio.h>
 
struct example {
    unsigned char a : 1;
    unsigned char b : 1;
    unsigned char c : 1;
    unsigned char d : 1;
    unsigned char e : 1;
    unsigned char f : 1;
    unsigned char g : 1;
    unsigned char h : 1;
};
 
 
int main(int argc, char *argv[])
{
    struct example ex1 = {1, 1, 1, 1, 1, 1, 1, 1};
    struct example ex2 = {1, 1, 1, 1, 1, 1, 1, 0};
 
 
    unsigned char   c_ex1 = *(unsigned char*)&ex1;
    unsigned char   c_ex2 = *(unsigned char*)&ex2;
 
    printf ("\x1b[40m\x1b[36m [DEBUG] ## %s: %s: %d: c_ex1 = [%u] \x1b[0m\n", __FILE__, __FUNCTION__, __LINE__, c_ex1);
    printf ("\x1b[40m\x1b[36m [DEBUG] ## %s: %s: %d: c_ex1 = [%u] \x1b[0m\n", __FILE__, __FUNCTION__, __LINE__, c_ex2);
 
    if (c_ex1 == c_ex2) {
        printf("True...\n");
    }
    else {
        printf("False...\n");
    }
 
 
    return 0;
}

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

라스코니의 이미지

\x1b[40m\x1b[36m
좋은 거 알았네요. 간단한 출력에는 굳이 ncurses를 쓸 필요가 없겠네요.

댓글 달기

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