C#(VS2013)の漢字<-->数値変換について

このQ&Aのポイント
  • C#(VS2013)の漢字、数値変換に関する質問です。
  • 文字を数値、数値を文字に変換するコードについて説明します。
  • 文字が'A'の場合は相互に変換できますが、'換'の場合は変換できません。
回答を見る
  • ベストアンサー

C#(VS2013)の漢字<-->数値変換について

C#(VS2013)の漢字、数値変換に関する質問です。 下記のコードは、文字を数値、数値を文字に変換するものです。 この場合、文字が"A"の場合は、相互に変換できますが、 文字が "換" の場合は、変換出来ません。 Q1)この件に関しまして、回答、コメント頂けますと大変有難いです。 //Project: c:\wk_VS2013ACs\TT_CharCLR.sln using System; using System.Text; public static class Program { public static void Main() { Char c; Int32 n; string str = "シフトJISへ変換"; Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS"); byte[] bytes = sjisEnc.GetBytes(str); Console.WriteLine(BitConverter.ToString(bytes)); // 出力:83-56-83-74-83-67-4A-49-53-82-D6-95-CF-8A-B7 // Convert number <-> character using C# casting // c = (Char)0x95CF; 変 // c = (Char)0x8AB7; 換 //c = (Char)65; c = (Char)0x8AB7; //<------旨く行かず Console.WriteLine(c); // Displays "A" n = (Int32)c; Console.WriteLine(n); // Displays "65" c = unchecked((Char)(65536 + 65)); //============= Console.WriteLine(c); // Displays "A" // Convert number <-> character using Convert c = Convert.ToChar(65); Console.WriteLine(c); // Displays "A" n = Convert.ToInt32(c); Console.WriteLine(n); // Displays "65" // This demonstrates Convert's range checking try { c = Convert.ToChar(70000); // Too big for 16 bits // c = Convert.ToChar(0x95CF); // Too big for 16 bits Console.WriteLine(c); // Doesn't execute } catch(OverflowException) { Console.WriteLine("Can't convert 70000 to a Char."); } // Convert number <-> character using IConvertible c = ((IConvertible)65).ToChar(null); Console.WriteLine(c); // Displays "A" n = ((IConvertible)c).ToInt32(null); Console.WriteLine(n); // Displays "65" Console.ReadKey(); }//public static void Main() { }//namespace

質問者が選んだベストアンサー

  • ベストアンサー
  • wormhole
  • ベストアンサー率28% (1620/5655)
回答No.1

char型で扱う文字コードはunicodeですから、sjisコードでの値を用いたところで勝手にunicodeでの値に変換してくれたりはしません。

関連するQ&A

  • C#の質問

    コンソールからの入力で2つの整数を取得したいのですが、 下記のように、2行に渡って取得する他ないのでしょうか? Console.WriteLine("何行何列ですか?"); int gyou = Convert.ToInt32(Console.ReadLine()); int retu = Convert.ToInt32(Console.ReadLine()); 私としましては、ユーザーに2,3のように1行で入力してもらって、 gyouには2をretuには3を保存したいのですが・・・。 そんなことは可能でしょうか? どなたかご教授お願いいたします。

  • .NET1.1でPING処理(C#からの変換)

    VB2002+WIN2000を使用。 リモート端末へのアクセス前に起動確認処理としてPINGを使い、電源OFF時の待ち時間を減らしたいと考えています。 ○PINGの他に導通確認できる手軽なものがあるのでしたら教えてください。 PINGの処理はネットで検索した結果C#(1.1)のものでしたら発見できたため、それを利用しようと思っています。(サイトでもVBへの変換は簡単にできるとあったので^_^;) 自分なりに変換してみましたがエラーが発生してしまい原因/対応方が分かりません。 ぜひご教授下さい。よろしくお願いいたします。 (補足が必要であれば記述します。) 【元からの変更】 ・引数はなしにし、固定にしました。 ・Button1の処理に記述しました。 ・参照設定でSystem.Managementを追加しました。 【エラー】 スレッド '<名前がありません>' (0x59c) はコード 0 (0x0) で終了しました。 'System.Management.ManagementException' のハンドルされていない例外が system.management.dll で発生しました。 追加情報 : 無効なクラスです 【予想】 searcherにGetがない? 対策が分からず… ----- 変更プログラム ------ Imports System Imports System.Management Dim arg As String arg = "192.168.0.1" 'クエリ文字列の設定() Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher() searcher = New ManagementObjectSearcher("select * from Win32_PingStatus where address = '" & arg & "'") ' クエリ結果のとりだし Dim mo As ManagementObject 'エラー箇所 For Each mo In searcher.Get Dim i As Integer ' 結果のプロパティのチェックと状態の表示 If mo.Properties("StatusCode").Value = "" Or Convert.ToInt32(mo.Properties("StatusCode").Value) <> 0 Then Console.WriteLine(arg + ":稼働していません") Else Console.WriteLine(arg + ":稼働中") Console.WriteLine("IPAddress:" & mo.Properties("ProtocolAddress").Value) Console.WriteLine("ResponseTime:" & mo.Properties("ResponseTime").Value) End If Next Console.WriteLine("----------------") ------ 元プログラム(C#) ---------------------- using System; using System.Management; class PingExec { public static void Main(string[] args) { if(args.Length > 0) { foreach(string arg in args) { // クエリ文字列の設定 ManagementObjectSearcher searcher = new ManagementObjectSearcher( "select * from Win32_PingStatus where address = '" + arg + "'"); // クエリ結果のとりだし foreach( ManagementObject mo in searcher.Get() ) { // 結果のプロパティのチェックと状態の表示 if(mo.Properties["StatusCode"].Value == null || Convert.ToInt32(mo.Properties["StatusCode"].Value) != 0) { Console.WriteLine(arg + ":稼働していません"); } else { Console.WriteLine(arg + ":稼働中"); Console.WriteLine("IPAddress:" + mo.Properties["ProtocolAddress"].Value); Console.WriteLine("ResponseTime:" + mo.Properties["ResponseTime"].Value); } } Console.WriteLine("----------------"); } } } }

  • c#でサンプルゲームを作ってみた

    c#でサンプルゲームを作ってみたのですがエラーがでるので間違っている所を指摘してくださいm(__)m using System; class test1 { public int HP; public int ATK; public int DF; } public class test2 { public static void Main() { test1 player1 = new test1(); test1 player2 = new test1(); player1.HP = 150; player2.HP = 150; char ch; char ken; char zyuu; char chois; int buki; for(;;){ do{ Console.WriteLine(" 使う武器を選んでください"); Console.WriteLine("¥n"); Console.WriteLine(" 1. 刀 "); Console.WriteLine("¥n"); Console.WriteLine(" 2. 拳銃 "); Console.WriteLine("¥n"); Console.WriteLine(" 3. 素手 "); Console.WriteLine(" 終了させたい場合は e"); do{ ch = (char) Console.Read(); } while(ch == '¥n' | ch == '¥r'); }while(ch < '1' | ch > '3' & ch != 'n'); if(ch == 'n') break; Console.WriteLine("¥n"); switch(ch){ case '1': Console.WriteLine(" どの刀を使いますか?"); Console.WriteLine(" 1. 太刀"); Console.WriteLine(" 2薙刀"); ken = (char) Console.Read(); while(ken == '¥n' | ken == '¥r'); Console.WriteLine("¥n"); switch(ken){ case '1': buki = 15; break; case '2': buki = 14; break; } case '2': Console.WriteLine(" どの銃を使いますか?"); Console.WriteLine(" 1.マシンガン"); Console.WriteLine(" 2.リボルバー"); zyuu = (char) Console.Read(); while(zyuu == '¥n' | zyuu == '¥r'); Console.WriteLine("¥n"); switch(zyuu){ case'1': buki = 10; break; case'2': buki = 15; break; } case'3': buki = 8; break; } Console.WriteLine("敵が現れた!"); for(;;){ if(plyer1.HP < 0) break; else(player2.HP < 0 ) break; Console.WriteLine(" 1.攻撃¥n 2.防御"); chois = (char) Console.Read(); while(chois == '¥n' | chois == '¥r'); Console.WriteLine("¥n"); switch(chois){ case'1': Console.WriteLine("player1の攻撃!!"); player2.HP = player2.HP - (buki + 10) - 5; Console.WriteLine("%d, player2.HP") ; Console.WriteLine("player2の攻撃!!"); player1.HP = player1.HP - (20 - 5); break; case'2': Console.WriteLine(" player1はガードした!!"); Console.WriteLine("player2の攻撃!!"); Console.WriteLine(" しかしplayer1は攻撃を防いだ!"); break; } } } } }

  • C#の変数の範囲

    C#の変数の範囲 質問させてください。 以下は、ネットに掲載されていたC#の問題です。 ~ここから~ 下記のC#のコードを実行した場合、"Hello World!"と二行表示されます。 using System; class Program { static void Main(string[] args) { string s = "Hello"; Action a = () => Console.WriteLine(s); s += " World!"; a(); Console.WriteLine(s); } これを一行目だけ"Hello"と表示される場合、 Action a = () => Console.WriteLine(s);をどう書き換えればよいでしょうか。 1. Action a = () => Console.WriteLine("Hello!"); 2. Action<string> a = (s) => Console.WriteLine(s); 3. Action a = () => Console.WriteLine(t - " World!"); 4. string t = s; Action a = () => Console.WriteLine(t); 5. Action a = () => { string t = s; Console.WriteLine(t); }; ~ここまで~ 正解は4だそうですが、「何故」そうなるかがわかりません。 汗 私としては、1.4.も題意を満たす気がするのですが・・・。 お知恵をお貸しください。 出展 http://www.atmarkit.co.jp/fdotnet/extremecs/extremecs_07/extremecs_07_10.html

  • C#でコンパイルができない。

    C#のベータ版をセットアップして以下のサンプルプログラムを コンパイルしたところ、エラーがでました。何がいけないのでしょうか?OSはWin98です。 css001.cs(7,3): error CS0117: 'System.Console' does not contain a definition for 'Writeline' using System; プログラムリスト public class CSS001 { public static void Main(string[] args) { Console.Writeline("Hello World"); } }

  • C# 猫でもわかる・・・ のプログラムで質問です。

    猫でもわかる・・・のページでC#の勉強させてもらってるのですが、 解らないところが出たので教えてください。 using System; class dowhle01 { public static void Main() { Console.Write("数字を入力してください(1-9) --- "); string strInput = Console.ReadLine(); if (strInput.Length >= 2) return; if (!char.IsDigit(strInput[0]) || strInput[0] == '0') return; int n = strInput[0] - '0'; string mystr = ""; int i = 1, sum = 0; do { sum += i; mystr += string.Format("{0} + ", i); i++; } while (i <= n); char[] trimchar = new char[] { '+', ' ' }; mystr = mystr.TrimEnd(trimchar); mystr += " = "; mystr += sum; Console.WriteLine(mystr); } } このプログラムの中の int n = strInput[0] - '0'; この部分なんですけど、 これはint型に直してるってことでしょうか? でも、普通int型にするなら、 int n = int.Parse(strInput);ですよね? こういうやり方もあるって意味なんですかね? それとも、何か特別な意味があるのでしょうか? 教えて下さい。よろしくお願いします。

  • パイプを用いた通信 C#とMATLAB

    パイプを使用しC#から送信したデータをMATLABで受信することは可能でしょうか?   もし可能であるならばどのようにすればよいのでしょうか。 以下のプログラムで行っているのですがMATLAB側で受信ができず -1がかえってきてしまいます C言語で受信する場合はうまくいくのですがMATLABを使用するとファイルのopneができません。 以下C#・MATLABプログラム C# <プログラム> 送信側 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Pipes; using System.IO; namespace PipeTest { class Program { static void Main(string[] args){ Console.WriteLine("パイプ接続待ち..."); NamedPipeServerStream pipe = new NamedPipeServerStream("test"); pipe.WaitForConnection(); Console.WriteLine("送信(キーを押すと終了)"); StreamWriter stw = new StreamWriter(pipe); stw.AutoFlush = true; while(Console.KeyAvailable == false) { stw.WriteLine("This is a test"); System.Threading.Thread.Sleep(500); } Console.WriteLine("終了"); pipe.Close(); } } } MATLAB <プログラム> 受信側 fp = fopen('C:\\\\.\\pipe\\test');

  • C# この文法でコンパイルが通らないのは何故?

    下記のような2つのプログラムがあり、一方はコンパイルが通らず、もう一方はコンパイルが通ります。 文法上の違いはさほどないと思うのですが、何故このような結果になるのでしょうか? /////////////////////////コンパイルNG///////////////////////// using System; class Class1{ public static void Main(){ Class2 x; //違い! Class2 xをここで定義 try{x = new Class2(100);} catch{} Console.WriteLine(x.z); } } class Class2{ public int z; public Class2(int x){ z=x; } } /////////////////////////////////////////////////////////// /////////////////////////コンパイルOK///////////////////////// using System; class Class1{ static Class2 x; //違い! Class2 xをここで定義 public static void Main(){ try{x = new Class2(100);} catch{} Console.WriteLine(x.z); } } class Class2{ public int z; public Class2(int x){ z=x; } } ///////////////////////////////////////////////////////////

  • Visual Studio 2017C#

    下記のVisual Studio 2017 C# 19行目のXの定義がありません。 と出ました。 11行目で定義していると思うのですけど…。 どういうことなのか教えてください。 ご多忙のところ恐れ入りますが、ご回答のほどよろしくお願いします。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace jump25 { class Test { public int x = 10; } class Program { public static void Main(string[] args) { Test obj = new Test(); int y = object.x; Console.WriteLine(y); } } }

  • C#ド素人の質問

    今日からc#を始めたド素人です windows8 のmicrosoft visual express 2012 for windows8でやっているのですが using System; class Sample1 { public static int Main() { Console.WriteLine("ようこそC#へ!"); return 0; } } 上のことをしたときにエラーが三つ発見されConsoleの部分に赤線が出ます どうすれば正常に機能しますか?

専門家に質問してみよう