달력

2

« 2025/2 »

  • 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
2016. 7. 10. 11:30

형 변환 예제 프로그래밍/C#2016. 7. 10. 11:30

16진수 문자열과 숫자 형식 간 변환


https://msdn.microsoft.com/ko-kr/library/bb311038.aspx



<string에서 각 문자의 16진수 값을 가져오기>


string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // 문자에 대한 정수 값 얻기
    int value = Convert.ToInt32(letter);
    // 10진수 값을 문자열 형식의 16진수 값으로 변환
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
/* Output:
   Hexadecimal value of H is 48
    Hexadecimal value of e is 65
    Hexadecimal value of l is 6C
    Hexadecimal value of l is 6C
    Hexadecimal value of o is 6F
    Hexadecimal value of   is 20
    Hexadecimal value of W is 57
    Hexadecimal value of o is 6F
    Hexadecimal value of r is 72
    Hexadecimal value of l is 6C
    Hexadecimal value of d is 64
    Hexadecimal value of ! is 21
 */



<16진수 문자열의 각 값에 해당하는 char을 가져오기>


string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21"; string[] hexValuesSplit = hexValues.Split(' '); foreach (String hex in hexValuesSplit) { // 16진수로 표현된 수를 정수로 변환 int value = Convert.ToInt32(hex, 16); // 정수 값에 해당하는 문자 얻기 string stringValue = Char.ConvertFromUtf32(value); char charValue = (char)value; Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue); } /* Output: hexadecimal value = 48, int value = 72, char value = H or H hexadecimal value = 65, int value = 101, char value = e or e hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 6F, int value = 111, char value = o or o hexadecimal value = 20, int value = 32, char value = or hexadecimal value = 57, int value = 87, char value = W or W hexadecimal value = 6F, int value = 111, char value = o or o hexadecimal value = 72, int value = 114, char value = r or r hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 64, int value = 100, char value = d or d hexadecimal value = 21, int value = 33, char value = ! or ! */



<16진수 string을 int로 변환>


string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274



<16진수 string을 float로 변환>


string hexString = "43480170";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);

byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);

// Output: 200.0056    



<byte 배열을 16진수 string으로 변환>


byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };

string str = BitConverter.ToString(vals);
Console.WriteLine(str);

str = BitConverter.ToString(vals).Replace("-", "");
Console.WriteLine(str);

/*Output:
  01-AA-B1-DC-10-DD
  01AAB1DC10DD
 */



<예제>

byte[] back = { 0x42, 0x41, 0x43, 0x4B };

Console.WriteLine("{0}", BitConverter.ToString(back).Replace("-", ""));

Console.WriteLine("{0}{1}{2}{3}", (char)back[0], (char)back[1], (char)back[2], (char)back[3]);

Console.WriteLine("{0}", Encoding.UTF8.GetString(back));

Array.Reverse(back);

Console.WriteLine("{0}", Encoding.UTF8.GetString(back));


// 결과

4241434B

BACK

BACK

KCAB




BitConverter 클래스

https://msdn.microsoft.com/ko-kr/library/system.bitconverter(v=vs.110).aspx


1. 기본 데이터 형식(base data types)을 바이트 배열로 변환하고, 바이트 배열을 기본 데이터 형식으로 변환합니다.


2. How to: Convert a byte Array to an int : https://msdn.microsoft.com/en-us/library/bb384066.aspx







바이트 배열을 문자열로 변환

http://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array


1. LINQ example

public static byte[] StringToByteArray(string hex) {

    return Enumerable.Range(0, hex.Length)

                     .Where(x => x % 2 == 0)

                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))

                     .ToArray();

}


2. the shorter verison of LINQ example

Enumerable.Range(0, hex.Length / 2) .Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16)) .ToArray();


3. The fatest conversion

public static byte[] StringToByteArrayFastest(string hex) {

        if (hex.Length % 2 == 1)

            throw new Exception("The binary key cannot have an odd number of digits");


        byte[] arr = new byte[hex.Length >> 1];


        for (int i = 0; i < hex.Length >> 1; ++i)

        {

            arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));

        }


        return arr;

    }


    public static int GetHexVal(char hex) {

        int val = (int)hex;

        //For uppercase A-F letters:

        return val - (val < 58 ? 48 : 55);

        //For lowercase a-f letters:

        //return val - (val < 58 ? 48 : 87);

        //Or the two combined, but a bit slower:

        //return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));

    }


4. another example using byte.Parse()

public static byte[] ConvertHexStringToByteArray(string hexString)

{

    if (hexString.Length % 2 != 0)

    {

        throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));

    }


    byte[] HexAsBytes = new byte[hexString.Length / 2];

    for (int index = 0; index < HexAsBytes.Length; index++)

    {

        string byteValue = hexString.Substring(index * 2, 2);

        HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);

    }


    return HexAsBytes; 

}


5. 원래대로

byte[] b = .........;

BitConverter.ToString(b).Replace("-", "");






Converting a byte to a binary string in c#


https://stackoverflow.com/questions/3581674/converting-a-byte-to-a-binary-string-in-c-sharp


string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0');

// produces "00111111"



To change full array:


byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };

string[] b = a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ).ToArray();

// Returns array:

// 00000010

// 00010100

// 11001000

// 11111111

// 01100100

// 00001010

// 00000001




To change your byte array to single string, with bytes separated with space:


byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };

string s = string.Join( " ",

    a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );

// Returns: 00000001 00001010 01100100 11111111 11001000 00010100 00000010




if ordering of bytes is incorrect use IEnumerable.Reverse():


byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };

string s = string.Join( " ",

    a.Reverse().Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );

// Returns: 00000010 00010100 11001000 11111111 01100100 00001010 00000001




public static String convert(byte b)

{

    StringBuilder str = new StringBuilder(8);

            int[] bl  = new int[8];


    for (int i = 0; i < bl.Length; i++)

    {               

        bl[bl.Length - 1 - i] = ((b & (1 << i)) != 0) ? 1 : 0;

    }


    foreach ( int num in bl) str.Append(num);


    return str.ToString();

}






'프로그래밍 > C#' 카테고리의 다른 글

제네릭 요약  (0) 2016.08.02
LINQ 정리  (1) 2016.07.28
StringBuilder 클래스  (0) 2016.07.09
대리자 Action, Func  (0) 2016.07.08
String.Format 메서드  (0) 2016.06.28
:
Posted by 지훈2