C# hex to ascii

前端 未结 4 539
有刺的猬
有刺的猬 2020-12-03 14:05

I\'m trying to convert a String of hex to ASCII, using this:

public void ConvertHex(String hexString)
{
    StringBuilder sb = new StringBuilder();

    for          


        
4条回答
  •  孤城傲影
    2020-12-03 14:41

    There are four three problems here:

    1. Since you're incrementing i by 2 on each iteration, you need to terminate at hexString.Length - 1. This doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.
    2. You're taking the wrong number of characters from hexString.
    3. hs is never used.
    4. You're not appending anything to sb.

    Try this:

    for (int i = 0; i < hexString.Length; i += 2)
    {
        string hs = hexString.Substring(i, 2);
        sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
    }
    

    Note that there's no need to qualify the types with their namespace, System (assuming you've referenced it at the top of the file with a using statement).

提交回复
热议问题