c++ stdout debug大法 ─ 懶得打開GDB時要怎麼印出記憶體內容

前言

基本上這是一篇廢文,我打字的同時在上DSnP的課,可是到目前為止還在複習C++基礎,只好上來發廢文(?)

code

/*
 * Version 
 * Author: WildfootW
 * GitHub: github.com/Wildfoot
 * Copyright (C) 2018 WildfootW All rights reserved.
 *
 */


#include <iostream>
#include <bitset>

using namespace std;

template <class T>
void print_memory(T & origin)
{
    union u
    {
        T object;
        unsigned char byte_arr[sizeof(T)];
    };
    u temp;
    temp.object = origin;
    for(size_t i = 0;i < sizeof(T); i++)
        printf("%02x ", temp.byte_arr[i]);
    printf("\n");

    bitset<sizeof(T) * 8> bin_temp(origin);
    cout << bin_temp << endl;
    return;
}

int main()
{
    double test_double = 31325.265;
    int test_int = 123;
    char test_char = 'A';
    print_memory(test_double);
    print_memory(test_int);
    print_memory(test_char);
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *