C++ Byte Pattern Output

Asked 2 years ago, Updated 2 years ago, 25 views

int dwValue = 33; For , 0x21000000

int dwValue = -33; I want to print it out in the format 0xdffffffff.

void show_binary(char* pAddr, int size)
{
    cout << "0x";
    char dwBuffer[20];
    int dwValue;

    for (int i = 0; i < size; i++) {
            dwValue = pAddr[i];
        sprintf(dwBuffer,"%02X", dwValue);
        cout << dwBuffer;
    }
    cout << endl;
}

The results are coming out like the bottom. Debugging it, I think the dwValue comes out weird when it's negative.

c++

2022-09-22 20:15

1 Answers

It looks like you're working on an Intel CPU-based window.

You can simply convert it to Little Endian.

[cling]$ #include<cstdio>
[cling]$ int i = 33
(int) 33
[cling]$ int di = -33
(int) -33
[cling]$ printf("0x%x\n", ((i>>24)&0xff) | ((i<<8)&0xff0000) | ((i>>8)&0xff00) | ((i<<24)&0xff000000))
0x21000000
[cling]$ printf("0x%x\n", ((di>>24)&0xff) | ((di<<8)&0xff0000) | ((di>>8)&0xff00) | ((di<<24)&0xff000000))
0xdfffffff


2022-09-22 20:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.