LoginSignup
6
7

More than 5 years have passed since last update.

C#でbyte出力する (16進、2進、10進)

Posted at

何番煎じかわかりませんが、自分用メモも兼ねて。
VisualStudio Codeで動作確認済みです。

using System;

namespace ConsoleApp_DotNetCore
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes;
            int val = 65534;

            Console.WriteLine("--- int convert to byte ---\n");
            Console.WriteLine("int value = {0}",val);

            string text = "";
            string tmp = "";

            Console.WriteLine("= HEX = = = = = = = = =");

            bytes = BitConverter.GetBytes(val);
            foreach(byte b in bytes)
            {
                text = string.Format("{0,3:X2}", b);
                Console.WriteLine(text);
                tmp = text + tmp;
            }
            Console.WriteLine("\n" + tmp + "\n");


            Console.WriteLine("= BIN = = = = = = = = =");
            text = "";
            tmp = "";

            bytes = BitConverter.GetBytes(val);
            foreach (byte b in bytes)
            {
                String s = Convert.ToString(b, 2);
                text = s.PadLeft(8,'0');
                Console.WriteLine(text);
                tmp =" "+ text + tmp;
            }
            Console.WriteLine("\n" + tmp + "\n");


            Console.WriteLine("= DEC = = = = = = = = =");
            text = "";
            tmp = "";

            bytes = BitConverter.GetBytes(val);
            foreach (byte b in bytes)
            {
                Console.WriteLine(b.ToString());
                tmp = " " + String.Format("{0,4}",b) + tmp;
            }
            Console.WriteLine("\n" + tmp + "\n");


            Console.WriteLine("キー入力すると終了します");
            Console.ReadLine();

        }
    }
}

実行結果

--- int convert to byte ---

int value = 65534
= HEX = = = = = = = = =
 FE
 FF
 00
 00

 00 00 FF FE

= BIN = = = = = = = = =
11111110
11111111
00000000
00000000

 00000000 00000000 11111111 11111110

= DEC = = = = = = = = =
254
255
0
0

    0    0  255  254

6
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7