Austin
Austin

Reputation: 83

Printing the value from a memory address in C++ as hex

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 = &num;
    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?

Upvotes: 6

Views: 3286

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596642

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

Upvotes: 3

rustyx
rustyx

Reputation: 85372

The CCs are the uninitialized stack memory tag, set by Visual C++ in debug mode.

Note that you also a strict aliasing violation at (int*)(q+i).

What you probably wanted is this:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int num;
    cout << "Enter an integer" << endl;
    cin >> num;

    unsigned char* q = (unsigned char*)&num;

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

}

Upvotes: 3

Related Questions