Reputation: 2947
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.
Upvotes: 0
Views: 404
Reputation: 2620
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));
}
Upvotes: 1
Reputation: 2947
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?
Upvotes: 1