I'm trying to make a program that takes in an integer value and then prints out the value of each of the four bytes in hex. So for 255 it should print out FF 00 00 00. This is what my code is looking like so far.
#include "pch.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int num;
cout << "Enter an integer" << endl;
cin >> num;
int* p = #
unsigned char* q = (unsigned char*)p;
for (int i = 0; i < 4; i++) {
cout<< hex <<*(int*)(q+i) << " ";
}
}
When I enter 255 it prints ff cc000000 cccc0000 cccccc00
What are the c's?
In your cout
statement, you are casting (q+i)
itself to an int*
pointer and then dereferencing it to get an int
value. That is wrong, because (q+i)
does not point at an int
, and dereferencing it as such will exceed the bounds of num
into surrounding memory when i > 0
.
You need to instead dereference (q+i)
as-is to get the unsigned char
it actually points to, and then cast THAT value to an [unsigned
] int
(or at least to an [unsigned
] short
) when printing it:
cout << hex << static_cast<int>(*(q+i)) << " ";
Also, an int
is not always 4 bytes on all systems, so you should not hard-code the size, use sizeof(int)
instead:
for (int i = 0; i < sizeof(num); i++)
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With