문제

32 비트 부호없는 int에 저장된 값을 가져다가 4 개의 숯으로 넣은 다음 각 숯의 정수 값을 문자열에 보관하고 싶습니다.

첫 번째 부분은 다음과 같이 생각합니다.

char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
도움이 되었습니까?

해결책

먼저 개별 바이트를 추출하려면 :

unsigned char a = orig & 0xff;
unsigned char b = (orig >> 8) & 0xff;
unsigned char c = (orig >> 16) & 0xff;
unsigned char d = (orig >> 24) & 0xff;

또는:

unsigned char *chars = (unsigned char *)(&orig);
unsigned char a = chars[0];
unsigned char b = chars[1];
unsigned char c = chars[2];
unsigned char d = chars[3];

또는 서명되지 않은 길고 4 문자의 결합을 사용하십시오.

union charSplitter {
    struct {
        unsigned char a, b, c, d;
    } charValues;

    unsigned int intValue;
};

charSplitter splitter;
splitter.intValue = orig;
// splitter.charValues.a will give you first byte etc.

업데이트 : Friol이 지적한 바와 같이, 솔루션 2와 3은 엔지니어가 아닙니다. 어느 바이트 a, b, c 그리고 d CPU 아키텍처에 따라 다릅니다.

다른 팁

"Orig"가 귀하의 값을 포함하는 32 비트 변수라고 가정 해 봅시다.

나는 당신이 다음과 같은 일을하고 싶다고 생각합니다.

unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;

char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);

그건 그렇고 이것이 항상 Endian 정확한지 확신하지 못합니다. (편집하다: 실제로, 비트 시프트 작업은 엔지니어의 영향을받지 않아야하기 때문에 엔디 언 맞습니다.

도움이 되었기를 바랍니다.

a union. (여기서 요청한대로 샘플 프로그램입니다.)

    #include <<iostream>>
    #include <<stdio.h>>
    using namespace std;

    union myunion
    {
       struct chars 
       { 
          unsigned char d, c, b, a;
       } mychars;

        unsigned int myint; 
    };

    int main(void) 
    {
        myunion u;

        u.myint = 0x41424344;

        cout << "a = " << u.mychars.a << endl;
        cout << "b = " << u.mychars.b << endl;
        cout << "c = " << u.mychars.c << endl;
        cout << "d = " << u.mychars.d << endl;
    }

제임스가 언급했듯이 이것은 플랫폼에 따라 다릅니다.

좀 빠지는:

char a = orig & 0xff;
orig >>= 8;
char b = orig & 0xff;
orig >>= 8;
char c = orig & 0xff;
orig >>= 8;
char d = orig & 0xff;

"각 값의 정수 값을 문자열에 저장한다는 의미가 확실하지 않습니다. 회전하고 싶습니까? 0x10111213 ~ 안으로 "16 17 18 19", 또는 무엇을?

16 진수 :

sprintf(buffer, "%lX", orig);

10 진수 :

sprintf(buffer, "%ld", orig);

사용 snprintf 버퍼 오버플로를 피하기 위해.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top