所謂Base64を実装する際の手順なのですが、LINQを使わずに以下の2進数に変換した文字列をどのように展開できるでしょうか
参考サイト
string text = "あいうえお" // 変更したい文字列を2進数に変換する byte[] bytes = encoding.GetBytes(text); //この部分で、2進数文字列に展開しています。 char[] bits = bytes.SelectMany(octet => Convert.ToString(octet, 2).PadLeft(8, '0')) .ToArray();
char[] bits変数の中身でLINQのselectmanyやラムダを使わない方法を知りたいです。
宜しくお願い致します。
追記___
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Base64 { class Program { public static char[] conversionTable = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; static void Main(string[] args) { Console.WriteLine("文字を入力してください"); string text = Console.ReadLine(); Encoding encoding = new UTF8Encoding(); string aaa = Encode(text, encoding); Console.WriteLine($"{aaa}"); Console.ReadKey(); } public static string Encode(string text, Encoding encoding) { //stringビルダー型の変数を初期化 StringBuilder sb = new StringBuilder(); // 変更したい文字列を2進数に変換する byte[] bytes = encoding.GetBytes(text); //LINQを使わず文字列に展開 var list = new List<string>(); foreach (var octet in bytes) { list.Add(Convert.ToString(octet, 2).PadLeft(8, '0')); } var bits = list.ToArray(); var bit6 = ""; for (int i = 0; i < bits.Length; i++) { bit6 += bits[i]; //6ビット文字列を対応表で変換 if (bit6.Length == 6) { int tableIndex = Convert.ToInt32(bit6, 2); sb.Append(conversionTable[tableIndex]); bit6 = string.Empty; } if (i == bits.Length - 1 && bit6.Length != 0) { var padCount = 6 - bit6.Length; for (int j = 0; j < padCount; j++) bit6 += "0"; var tableIndex = Convert.ToInt32(bit6, 2); //ここでインデックスが配列の境界外ですとエラーが出ます sb.Append(conversionTable[tableIndex]); } } while (sb.Length % 4 != 0) sb.Append("="); return sb.ToString(); } } }
回答2件
あなたの回答
tips
プレビュー