Convert string to hex-string in C#

后端 未结 5 820
说谎
说谎 2020-11-28 06:10

I have a string like \"sample\". I want to get a string of it in hex format; like this:

  \"796173767265\"

Please give the

5条回答
  •  忘掉有多难
    2020-11-28 06:35

    First you'll need to get it into a byte[], so do this:

    byte[] ba = Encoding.Default.GetBytes("sample");
    

    and then you can get the string:

    var hexString = BitConverter.ToString(ba);
    

    now, that's going to return a string with dashes (-) in it so you can then simply use this:

    hexString = hexString.Replace("-", "");
    

    to get rid of those if you want.

    NOTE: you could use a different Encoding if you needed to.

提交回复
热议问题