如何在c#中将byte []转换为字符串

时间:2014-12-16 06:34:28

标签: c# entity-framework

为了防止并发,我已经包含了一个Timestamps类型的字段版本。我不知道如何将版本值转换为字符串。请帮我解决这个问题。

using (MMP2012Entities context = new MMP2012Entities())
{
    var res = (from i in context.LIN_Laundry_Issues
    join sub in context.LIN_Laundry_Iss_Sub on i.Issue_Number equals sub.Issue_Number
    join it in context.MMP_Items on sub.Item_Id equals it.id
    where i.Issue_Number==id && i.Hospital_Id==hospid && sub.Status_ind==1
    select new Laundry_IssueRecieptList
    {
        Issue_Date = i.Issue_Date,
        Collected_By = i.Collected_By,
        Authorised_By = i.Authorised_By,
        Laundry_Id = i.Laundry_Id,
        Item_Id = sub.Item_Id,
        Item_name = it.Name,
        Qty_Issued = sub.Qty_Issued,
        Rate = sub.Rate,
        Issue_Number=i.Issue_Number,
        subissueid=sub.Laundry_Trans_Sub_Id,
        Status_ind=sub.Status_ind,
        version=sub.Version
    }).ToList();
    return res;
}

3 个答案:

答案 0 :(得分:0)

您可以使用此功能:

private string ByteArrayToString(byte[] ba)
{
    StringBuilder hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba) {
        hex.AppendFormat("{0:x2}", b);
    }

    return hex.ToString();
}

并反转为

private byte[] StringToByteArray(string hexString)
{
    int length = hexString.Length;
    int upperBound = length / 2;
    if (length % 2 == 0) {
        upperBound -= 1;
    } else {
        hexString = "0" + hexString;
    }
    byte[] bytes = new byte[upperBound + 1];
    for (int i = 0; i <= upperBound; i++) {
        bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
    }

    return bytes;
}

答案 1 :(得分:0)

假设你正在使用UTF8(如果没有使用System.Text.Encoding.XXX.GetString(bytes)下的正确对象;

string str = System.Text.Encoding.UTF8.GetString(bytes);

答案 2 :(得分:0)

        public static string TimestampToString(this System.Data.Linq.Binary binary)

        {
            byte[] binarybytes = binary.ToArray();

            string result = "";
            foreach (byte b in binarybytes)
           {
                result += b.ToString() + "|";
            }
            result = result.Substring(0, result.Length - 1);
            return result;
       }

        public static System.Data.Linq.Binary StringToTimestamp(this string s)
        {
            string[] arr = s.Split('|');
            byte[] result = new byte[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                result[i] = Convert.ToByte(arr[i]);
            }
            return result;
        }