기본 콘텐츠로 건너뛰기

C# - Int Byte Byte[] Hex 정리

INT / HEX간 변환방법 
Int -> Hex : String str = 123.ToString("X");//"7B"
Hex -> Int : int num = int.Parse("123", System.Globalization.NumberStyles.HexNumber); // 291
Hex -> Int 다른방법 : string hex = "ABC"; int myInt = Convert.ToInt32(hex, 16); 
//Convert.ToInt32("바꾸고 싶은 숫자", "진수");, 여기서 진수는 2,8,10,16진수만 가능 

출처 : Hex Handling in C#


Byte => HEX 변환방법

byte b = 32;
string hexval = b.ToString ('X2');//첫번째 방법
Console.WriteLine("{0:X}",b);//두번째 방법

출처 : Byte to Hex


Byte[] => HEX 변환방법//첫번째 방법
Byte[] Bytes = {0xFF, 0xD0, 0xFF, 0xD1};// to "FFD0FFD1"
String byteToHex(Byte[] ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
       sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();
}
//두번째 방법
Byte[] Bytes = {0xFF, 0xD0, 0xFF, 0xD1}// to "FF-D0-FF-D1" 
BitConverter.ToString(Bytes);//-가 보기 흉하다면 replace하면 된다.

//세번째 방법(가장 확실한 방법같음)
public static string HexStr(byte[] p) {
char[] c=new char[p.Length*2 + 2];byte b;c[0]='0'; c[1]='x';for(int y=0, x=2; y<p.Length; ++y, ++x) {b=((byte)(p[y ]>>4));c[x]=(char)(b>9 ? b+0x37 : b+0x30);b=((byte)(p[y ]&0xF));c[++x]=(char)(b>9 ? b+0x37 : b+0x30);}return new string(c);}//HexStr(new byte[]{0x00,0xDE,0xAD,0xBE,0xEF,0x99}) ==> "0x00DEADBEEF99"


출처: http://hong2da.tistory.com/111 [세상사는 향기-너와 내가 만들어 가는 세상]

댓글

이 블로그의 인기 게시물

C# - Windows Form 에 있는 control 찾기

// 아래 코드는 form 의 최상위 control만 찾을 수 있음. // panle, groubbox ... 내부에 있는 control은 찾지 못함. Control GetControlByName(string Name) {     foreach (Control c in this.Controls)         if (c.Name == Name)             return c;     return null; } // form 의 모든 control을 찾을 수 있음. string name = "btnBit" + (i + 1).ToString("D2"); var tmpBtn = this.Controls.Find(name, true).FirstOrDefault(); if (tmpBtn != null) {     if (value == 1) tmpBtn.BackColor = Color.Lime;     else tmpBtn.BackColor = Color.Gray; }

C# - Serial Port ASCII/HEX Format

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; namespace SerialTest1 {     public partial class Form1 : Form     {         delegate void MyDelegate();      //델리게이트 선언(크로스 쓰레드 해결하기 위한 용도)         bool SendForamt = true;          // true : ASCII   false : HEX         bool ReceiveFormat = true;       // true : ASCII   false : HEX         public Form1()         {             InitializeComponent();          ...