Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 526
Austin Avatar asked Feb 10 '19 21:02

Austin


1 Answers

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

like image 157
Remy Lebeau Avatar answered Oct 12 '22 18:10

Remy Lebeau