忍者ブログ
趣味+メモ用のブログです。 GNU/Linux関連、OSS関連情報、調査事項になるでしょうが、何を書くか分かりません。
[83] [82] [81] [80] [79] [78] [77] [76] [75] [74] [73]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

ログ用に、HEXダンプ用のクラス+演算子オーバーライドをつくってみた。
(C++って本当に不便!!)


■C++ソースコード
 1 
 2 #include <typeinfo>   // for type id
 3 #include <iostream>
 4 #include <sstream>
 5 #include <stdio.h>
 6 
 7 
 8 /* HEX DUMP出力用の クラス */
 9 class hexdump {
10   private:
11   hexdump(){};
12   std::string str_;
13 
14 public:
15   /* コンストラクタ */
16   hexdump(unsigned char *ptr, int size){
17     char buff[4];
18     std::stringstream ss;
19     ss.str("");
20     for( int i = 0; i < size; i++ ) {
21       snprintf( buff, sizeof(buff), "%02x ", ptr[i] );
22       ss << std::string(buff) ;
23     }
24     this->str_ = ss.str();
25   };
26   hexdump(         int   val):hexdump((unsigned char*)&val, sizeof(int)){};
27   hexdump(unsigned int   val):hexdump((unsigned char*)&val, sizeof(unsigned int)){};
28   hexdump(         short val):hexdump((unsigned char*)&val, sizeof(short)){};
29   hexdump(unsigned short val):hexdump((unsigned char*)&val, sizeof(unsigned short)){};
30   hexdump(void *val,int size):hexdump((unsigned char*)val, size){};
31 
32 
33 public:
34   /* 出力関数 */
35   const std::string& getss(void) const {
36     return this->str_;
37   };
38 };
39 
40 /* 演算子オーバーロ ード */
41 std::ostream& operator<<(std::ostream& os, const hexdump& hexobj)
42 {
43     return ( os << hexobj.getss() );
44 }
45 
46 
47 
48 
49 /* テスト用クラス */
50 class Foo {
51 private:
52   int a_; int b_;
53 public:
54   Foo(int a, int b) :a_(a), b_(b) {};
55 };
56 
57 int main(void ) {
58 
59   int i = 0x12345678;
60   std::cout << "[" << typeid(i).name() <<"] " <<  hexdump(i) << std::endl;
61   short s = 0x1234;
62   std::cout << "[" << typeid(s).name() << "] " <<  hexdump(s) << std::endl;
63   char str[] = "0123456789";
64   std::cout << "[" << typeid(str).name() << "] " <<  hexdump(str, sizeof(str)) << std::endl;
65   Foo foo(0x12, 0x34);
66   std::cout << "[" << typeid(foo).name() << "] " <<  hexdump(&foo, sizeof(foo)) << std::endl;
67 
68 
69   return 0;
70 }

■結果
$ g++ -std=gnu++11 -Wall hexdump.cpp
$ ./a.out
[i] i 78 56 34 12
[s] s 34 12
[A11_c] str 30 31 32 33 34 35 36 37 38 39 00
[3Foo] str 12 00 00 00 34 00 00 00
$ vim hexdump.cpp  
PR


忍者ブログ [PR]
カレンダー
04 2024/05 06
S M T W T F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
フリーエリア
最新コメント
最新トラックバック
プロフィール
HN:
一乗寺 又兵衛
性別:
男性
職業:
コンパイル
趣味:
コンパイル
バーコード
ブログ内検索