how to merge four hexa digits into 3 hexa digits in C#
consider the following code:
string x="3F"; //0011 1111
string y="3F"; //0011 1111
string result="FFF";
where x is 6 bits and y is 6 bits but each one comes from different place and merging them into 3 hex-decimal digits is the required operation...how to do that in C#. note: x,y max value is 3F so no overflow will occur.
开发者_如何学Goalso i need the reverse operation:
string i="bc8"; //1011 1100 1000
string o1="2F";//10 1111
string o2="08";//00 1000
how to get o1 and o2 from i.
thanks,
It's just two simple bit operations. You have to shift (<<
) the bits by six positions to the left and them or (|
) them with the lower six bits.
uint x = 0x3f
uint y = 0x3f
uint result = x << 6 | y;
To decompose, mask lower and shift upper six bits to separate them.
uint orig = 0xbc8;
uint x = orig >> 6;
uint y = orig & 0x3f;
Conversions to and from string are left as an additional exercise ;-)
I would say convert the string representation to integer.
Then use shifting to build the new int value from the 2 integers.
And then string it again.
string str1 = "3F";
string str2 = "3F";
int n1 = int.Parse(str1, NumberStyles.HexNumber);
int n2 = int.Parse(str2, NumberStyles.HexNumber);
int number = (n1 << 6) | n2;
return number.TosString("X");
Reverse should be done in similar way:
string str = "FFF";
int number = int.Parse(str, NumberStyles.HexNumber);
int n1 = number & 0x3F;
int n2 = number >> 6;
精彩评论