忍者ブログ
暇人おやじの暇なつぶやき
[60] [59] [58] [57] [56] [55] [54] [53] [52] [51] [50]
×

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

■サンプルを活用する

マイクロソフトの.NET Framework Developer Centerには様々なサンプルコードが記載されている
しかし残念ながらそのまま動くものと動かないものがある

何故か?
たいていのコードは標準的な書かれ方をしているため、またコンソールアプリとして書かれている場合が
多いのでVC++などの環境では動いても一瞬で終了するような事がある

   Console::WriteLine( HexTest::ToHexString( b ) );

コンソールへの出力で終わっているプログラムの場合には、その後に入力待ちを入れるなどの工夫が
必要である

   Console::ReadLine();

通常C++の入力待ちは cin で記載する場合がある
cincoutはC++ネイティブ(?)としてヘッダーiostreamに記載があるのでこれをincludeしないと使用できない
そこで、上述の Console::ReadLine();を利用するのが便利である

次のコードはbyte変換用のサンプルと、それをVC++で使う際に変更したコード
■MSのサンプル
----------------------------------------------
ref class HexTest
{
private:
   static array<Char>^hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

public:
   static String^ ToHexString( array<Byte>^bytes )
   {
      array<Char>^chars = gcnew array<Char>(bytes->Length * 2);
      for ( int i = 0; i < bytes->Length; i++ )
      {
         int b = bytes[ i ];
         chars[ i * 2 ] = hexDigits[ b >> 4 ];
         chars[ i * 2 + 1 ] = hexDigits[ b & 0xF ];

      }
      return gcnew String( chars );
   }

};

int main()
{
   array<Byte>^b = {0x00,0x12,0x34,0x56,0xAA,0x55,0xFF};
   Console::WriteLine( HexTest::ToHexString( b ) );
}
-------------------------------------------------------------

■実際のコード
----------------------------------------------
// hextest.cpp : メイン プロジェクト ファイルです。

#include "stdafx.h"

using namespace System;
ref class HexTest
{
private:
   static array<Char>^hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

public:
   static String^ ToHexString( array<Byte>^bytes )
   {
      array<Char>^chars = gcnew array<Char>(bytes->Length * 2);
      for ( int i = 0; i < bytes->Length; i++ )
      {
         int b = bytes[ i ];
         chars[ i * 2 ] = hexDigits[ b >> 4 ];
         chars[ i * 2 + 1 ] = hexDigits[ b & 0xF ];

      }
      return gcnew String( chars );
   }

};

int main(array<System::String ^> ^args)
{
   array<Byte>^b = {0x00,0x12,0x34,0x56,0xAA,0x55,0xFF};
   Console::WriteLine( HexTest::ToHexString( b ) );
   Console::ReadLine();
   return 0;
}
-------------------------------------------------------------

PR

コメント


コメントフォーム
お名前
タイトル
文字色
メールアドレス
URL
コメント
パスワード
  Vodafone絵文字 i-mode絵文字 Ezweb絵文字


トラックバック
この記事にトラックバックする:


忍者ブログ [PR]
カレンダー
08 2024/09 10
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
フリーエリア
最新CM
最新TB
プロフィール
HN:
忍者 シオ才
性別:
非公開
バーコード
ブログ内検索