开发者社区 问答 正文

如何将字节数组转换为十六进制字符串,反之亦然?

如何将字节数组转换为十六进制字符串,反之亦然?

展开
收起
保持可爱mmm 2020-01-08 17:04:31 618 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • 要么:

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

    要么:

    public static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-",""); }

    例如,这里还有更多的变体。

    反向转换将如下所示:

    public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; }

    Substring与结合使用是最佳选择Convert.ToByte。

    问题来源于stack overflow

    2020-01-08 17:04:54 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等