1

Hello I am working on a project. Get unsigned 16 bit numbers and average them. No problem with getting average but when I tried to print to the screen, it prints meaningless symbols. So I figured out that I must convert it to decimal. Vs2015 converts it but I want to do it myself because my code is for a microprocessor. Here is my simulation...

int main(){

uint32_t  x = 0x12345678;
unsigned char c[4];

c[0] = x >> 24;// least significant 
c[1] = x >> 16;
c[2] = x >> 8;
c[3] = x;   // most significant
cout << x << endl;
cout << c[0] << endl;
cout << c[1] << endl;
cout << c[2] << endl;
cout << c[3] << endl;
system("pause");
return 0;

}

Output:

305419896 


4
V
x
Roguebantha
  • 794
  • 3
  • 17

1 Answers1

1

The problem here is, that the inserter operator << will treat char variables as character and not as a number. So, if the char variable contains 65, it will not print 65 but 'A'.

You need to convert the value to an unsigned int.

So:

std::cout << static_cast<unsigned int>(c[0]) << "\n";

Then it will give you the expected output.

Armin Montigny
  • 11,761
  • 3
  • 15
  • 37