SW/C#

string byte copy 스트링 바이트 복사 Array.Copy 조합, combine

또난 2020. 7. 27. 22:38

string 문자열과 int 를 byte 배열로 변경....통신에 사용.

using System;
using System.IO;
using System.Text;

class MainClass {

  public static string ByteToString(byte[] strByte, int len) 
  {     
    string str = Encoding.Default.GetString(strByte, 0, len);    // 아스키 문자이상은 깨짐...0x128 
    return str; 
  }
  public static byte[] StringToByte(string str) 
  { 
    byte[] StrByte = Encoding.UTF8.GetBytes(str); 
    return StrByte; 
  }
  static string BytesToStringConverted(byte[] bytes)
  {
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
  }

  public static void DisplayArrayValues(Array arr, string name, int len)
  {
    // Get the length of one element in the array.
    int elementLength = Buffer.ByteLength(arr) / arr.Length;
    string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength);
    Console.Write( "{0}({1}) :", name, len);
    for (int ctr = 0; ctr < len; ctr++)
      Console.Write(formatString, arr.GetValue(ctr));
    Console.WriteLine();
  }
  public static byte[] makeHeadData(string id, string date)
  {
    string sumStr = id+date;    
    byte[] headCnt = BitConverter.GetBytes(sumStr.Length);
    Array.Reverse(headCnt); // Big Endian으로 처리함    
    byte[] ByteHead = new byte[sumStr.Length+headCnt.Length];    
    Array.Copy(StringToByte(sumStr), ByteHead, sumStr.Length);  
    Array.Copy(headCnt, 0, ByteHead,sumStr.Length, 4);
    //DisplayArrayValues(ByteHead, "ByteHead",ByteHead.Length);
    return ByteHead;
  }
  public static void Main (string[] args) 
  {
    string sendId = "MBCRF00600900LED0001";
    string sendDate = "20191121005016";
  

    byte[] makeHead = makeHeadData(sendId, sendDate);
    DisplayArrayValues(makeHead, "makeHead",makeHead.Length);
    Console.WriteLine(ByteToString(makeHead,makeHead.Length));

    byte[] buf = new byte[10];
    string sendData;
     buf[0] = Convert.ToByte('E');
     buf[1] = Convert.ToByte('n');
     buf[2] = Convert.ToByte('d');
     buf[3] = Convert.ToByte('F');
     buf[4] = Convert.ToByte('A');
     buf[5] = 255;
    
    sendData = ByteToString(buf, 7);
    string s3 = Convert.ToBase64String(buf);
    byte[] decByte3 = Convert.FromBase64String(s3);
    var hexString64 = BitConverter.ToString(decByte3);

    byte[] strbyte = StringToByte(sendData);
    var hexString = BitConverter.ToString(strbyte);
    Console.WriteLine ("================");
    Console.WriteLine(hexString);
    Console.WriteLine(hexString64);
    
    Console.WriteLine ("{0}",sendData);
    DisplayArrayValues(buf, "buf",6);
  }
}


Start
makeHead(38) : 4D 42 43 52 46 30 30 36 30 30 39 30 30 4C 45 44 30 30 30 31 32 30 31 39 31 31 32 31 30 30 35 30 31 36 00 00 00 22
MBCRF00600900LED000120191121005016"
================
45-6E-64-46-41-EF-BF-BD-00
45-6E-64-46-41-FF-00-00-00-00
EndFA�
buf(6) : 45 6E 64 46 41 FF
0
Finish

 

위에 대신 추가된 combine 함수 통해 처리..

 

using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
//using System.Runtime.Serialization;

class MainClass {

  public static string ByteToString(byte[] strByte, int len) 
  {     
    string str = Encoding.Default.GetString(strByte, 0, len);    // 아스키 문자이상은 깨짐...0x128 
    return str; 
  }
  public static byte[] StringToByte(string str) 
  { 
    byte[] StrByte = Encoding.UTF8.GetBytes(str); 
    return StrByte; 
  }
  static string BytesToStringConverted(byte[] bytes)
  {
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
  }

  public static void DisplayArrayValues(Array arr, string name, int len)
  {
    // Get the length of one element in the array.
    int elementLength = Buffer.ByteLength(arr) / arr.Length;
    string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength);
    Console.Write( "{0}({1}) :", name, len);
    for (int ctr = 0; ctr < len; ctr++)
      Console.Write(formatString, arr.GetValue(ctr));
    Console.WriteLine();
  }
  public static T[] Combine<T>(params T[][] arrays)
  {
    T[] ret = new T[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (T[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
  }
  /*
  public static byte[] Combine(byte[] first, byte[] second)
  {
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
  }
  public static byte[] Combine(byte[] first, byte[] second, byte[] third)
  {
    byte[] ret = new byte[first.Length + second.Length + third.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
                     third.Length);
    return ret;
  }
  */
  public static byte[] makeHeadData(string id, string date)
  {
    string sumStr = id+date;    
    byte[] headCnt = BitConverter.GetBytes(sumStr.Length);
    Array.Reverse(headCnt); // Big Endian으로 처리함        
    byte[] ByteHead = Combine(StringToByte(sumStr), headCnt);    
    //DisplayArrayValues(ByteHead, "ByteHead",ByteHead.Length);
    return ByteHead;
  }
    // Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}
    
  public static Object ByteArrayToObject(byte[] arrBytes)
  {
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = binForm.Deserialize(memStream);
        return obj;
    }
  }
    
  public static void Main (string[] args) 
  {
    string sendId = "MBCRF00600900LED0001";
    string sendDate = "20191121005016";
    string sendDate2 = "ABCD";
    int sendCnt2 = 20;
    byte[] combineHead = Combine(StringToByte(sendId), StringToByte(sendDate), StringToByte(sendDate2), BitConverter.GetBytes(sendCnt2));
    DisplayArrayValues(combineHead, "combineHead",combineHead.Length);
    
    byte[] makeHead = makeHeadData(sendId, sendDate);
    DisplayArrayValues(makeHead, "makeHead",makeHead.Length);
    Console.WriteLine(ByteToString(makeHead,makeHead.Length));

    byte[] buf = new byte[10];
    string sendData;
     buf[0] = Convert.ToByte('E');
     buf[1] = Convert.ToByte('n');
     buf[2] = Convert.ToByte('d');
     buf[3] = Convert.ToByte('F');
     buf[4] = Convert.ToByte('A');
     buf[5] = 255;
     Console.WriteLine ("================");
     string strcon = BytesToStringConverted(buf);
    Console.WriteLine ("strcon {0}",strcon[5]);
    byte[] strconhex = ObjectToByteArray(strcon);
    DisplayArrayValues(strconhex, "strconhex",7);
    
    
    sendData = ByteToString(buf, 7);
    string s3 = Convert.ToBase64String(buf);
    byte[] decByte3 = Convert.FromBase64String(s3);
    var hexString64 = BitConverter.ToString(decByte3);

    byte[] strbyte = StringToByte(sendData);
    var hexString = BitConverter.ToString(strbyte);
    Console.WriteLine ("================");
    Console.WriteLine(hexString);
    Console.WriteLine(hexString64);
    
    Console.WriteLine ("{0}",sendData);
    DisplayArrayValues(buf, "buf",6);
  }
}

/// 실행.
Start
combineHead(42) : 4D 42 43 52 46 30 30 36 30 30 39 30 30 4C 45 44 30 30 30 31 32 30 31 39 31 31 32 31 30 30 35 30 31 36 41 42 43 44 14 00 00 00
makeHead(38) : 4D 42 43 52 46 30 30 36 30 30 39 30 30 4C 45 44 30 30 30 31 32 30 31 39 31 31 32 31 30 30 35 30 31 36 00 00 00 22
MBCRF00600900LED000120191121005016"
================
strcon �
strconhex(7) : 00 01 00 00 00 FF FF
================
45-6E-64-46-41-EF-BF-BD-00
45-6E-64-46-41-FF-00-00-00-00
EndFA�
buf(6) : 45 6E 64 46 41 FF
0
Finish