I have two values. one string in hex. another string in binary. Have to convert the first string in binary and apply "AND" to them.
string mask = "2F"; // binary value of hex would be 0010 1111
string binary = "0010 0000";
// convert mask to binary
string binaryMask = ConvertToString(mask); // result must be 0010 1111;
string result = binaryMask & binary; // AND them both - result : 0010 0000
First, remove whitespace from your binary
string (if you are not sure about input, you can remove whitespace on both strings):
string mask = "2F";
/* You can use "0010 0000".Trim().Replace(" ", "");
to make sure there is no whitespace at beginning/end
of the string */
string binary = "0010 0000".Replace(" ", "");
Convert both values to numeric:
// You can use .TryParse() here, to make sure if input is valid.
var a = short.Parse(mask, System.Globalization.NumberStyles.HexNumber);
// or var a = Convert.ToInt32(mask, 16);
var b = Convert.ToInt32(binary, 2);
Apply AND
operator:
var c = a & b;
Convert the result to string
again:
string result = Convert.ToString(c, 2);
Output:
100000
I found a solution
string value = "2F";
string value2 = "00100000";
int value1Int = Convert.ToInt32(value, 16);
int value2Int = Convert.ToInt32(value2, 2);
var and = value1Int & value2Int;
var hex = and.ToString("X");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.