C++ char output

Asked 2 years ago, Updated 2 years ago, 23 views

You want to express the little endian by approaching the value in the variable with char* and reading each byte by byte.

For example,

    int dwValue = 33;
    char* pBuf = &dwValue;

    for(int i = 0; i < 4 ; i++){
        cout << hex << pBuf[i];
    }

Expected output result 21000000
Actual result: ? ~~
Since it's char, it comes out based on the ASCII code. What should I do?

c++

2022-09-22 13:19

1 Answers

Look at the example below and learn.

For your information, the decimal number 33 on the ASCII code is !.

[cling]$ int dwValue = 33;
[cling]$ char* pBuf = &dwValue;
input_line_4:2:8: error: cannot initialize a variable of type 'char *' with an rvalue of type 'int *'
 char* pBuf = &dwValue;
       ^      ~~~~~~~~
[cling]$ temp = (char*)&dwValue
(char *) "!"
[cling]$ temp[0]
(char) '!'
[cling]$ temp[1]
(char) '0x00'
[cling]$ temp[2]
(char) '0x00'
[cling]$ temp[3]
(char) '0x00'


2022-09-22 13:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.