c# manipulating a string as a hex code?

403 Views Asked by At

If I want to work with string to represent hexadecimal values, is there a way to make bitwise AND, bitwise OR and such between them?

I know there are types which can handle that, but I'd need to keep them as string.

2

There are 2 best solutions below

0
On BEST ANSWER

After reading commentaries and answer I choose to use byte array (thanks to Dusan)

Solution I picked :

All I had to do was to convert the string to byte when I need to use bitwise operator, and then back to string.

This links shows how How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

0
On

I don't know about such a type.

I usually use these methods :

     //check if string is in hex format.
    bool OnlyHexInString(string text)
    {
        for (var i = 0; i < text.Length; i++)
        {
            var current = text[i];
            if (!(Char.IsDigit(current) || (current >= 'a' && current <= 'f')))
            {
                return false;
            }
        }
        return true;
    }

Conversion from string hex to int is done here:

    public string HexToInt(string hexString)
    {
        hexString = hexString.Trim();
        hexString = hexString.ToLower();
        if (hexString.Contains("0x"))
            hexString = Regex.Replace(hexString, "0x", "");

        if (OnlyHexInString(hexString))
            return System.Convert.ToInt64(hexString, 16).ToString();
        else
            return "";
    }

Edit 1 I forgot to add the Int64.Parse() on the result if the result is not null or empty. Sorry for that.

Perform your actions and get the result back to hex string:

    public string IntToToHex(string integerAsAString)
    {
        if (!string.IsNullOrEmpty(integerAsAString))
        {
            Int64 integerValue = 0;

            bool parsed = Int64.TryParse(integerAsAString, out integerValue);

            if (parsed)
                return integerValue.ToString("X");

            else
                throw new Exception(string.Format("Couldn't parse {0} hex string!", integerAsAString));
        }
        else
            throw new Exception(string.Format("Couldn't parse {0} hex string!", integerAsAString));
    }