simplification of function

G

GTi

Can this be done different in C#

private ushort GetRQU(ushort regpos)
{
ushort pos;
ushort tmp;
ushort value = 0;
string inBuff = "AA"; // EXAMPLE ONLY

tmp = (ushort)inBuff[0];
if(( tmp & 1 ) != 0) { value = (ushort)( value + 32768 ); }
if(( tmp & 2 ) != 0) { value = (ushort)( value + 16384 ); }
if(( tmp & 4 ) != 0) { value = (ushort)( value + 8192 ); }
if(( tmp & 8 ) != 0) { value = (ushort)( value + 4096 ); }
if(( tmp & 16 ) != 0) { value = (ushort)( value + 2048 ); }
if(( tmp & 32 ) != 0) { value = (ushort)( value + 1024 ); }
if(( tmp & 64 ) != 0) { value = (ushort)( value + 512 ); }
if(( tmp & 128 ) != 0) { value = (ushort)( value + 256 ); }
tmp = inBuff[1];
if(( tmp & 1 ) != 0) { value = (ushort)(value + 128); }
if(( tmp & 2 ) != 0) { value = (ushort)(value + 64); }
if(( tmp & 4 ) != 0) { value = (ushort)(value + 32); }
if(( tmp & 8 ) != 0) { value = (ushort)(value + 16); }
if(( tmp & 16 ) != 0) { value = (ushort)(value + 8); }
if(( tmp & 32 ) != 0) { value = (ushort)(value + 4); }
if(( tmp & 64 ) != 0) { value = (ushort)(value + 2); }
if(( tmp & 128 ) != 0) { value = (ushort)( value + 1 ); }
return ( value );
}


And a function that do it the other way back:
(this is a C function)

BYTE ComliSetReg(short a, unsigned short b )
{
BYTE ret;

ret=0;
if(a==0) /* LOW */
{
if(b & 1) ret = ret + 128;
if(b & 2) ret = ret + 64;
if(b & 4) ret = ret + 32;
if(b & 8) ret = ret + 16;
if(b & 16) ret = ret + 8;
if(b & 32) ret = ret + 4;
if(b & 64) ret = ret + 2;
if(b & 128) ret = ret + 1;
}
else /* HIGH */
{
if(b & 256) ret = ret + 128;
if(b & 512) ret = ret + 64;
if(b & 1024) ret = ret + 32;
if(b & 2048) ret = ret + 16;
if(b & 4096) ret = ret + 8;
if(b & 8192) ret = ret + 4;
if(b & 16384) ret = ret + 2;
if(b & 32768) ret = ret + 1;
}

return(ret);
}
 
M

Marc Gravell

What is it meant to do? regpos and pos aren't used in GetRQU, but otherwise
(and I may be reading it wrong here) it /looks/ like it simply reverses the
bits (left-to-right) - in which case surely the "undo" is to run it again?

Anyway, the answer is probably to use bit operators in a loop - i.e.
something like (in pseudo#)

uint currentBit = 32768;
for(each byte) {
for(0 to 7) {
if((tmp & 1) == 1) value |= currentBit; // add to mask
tmp >>= 1; // test next bit
add >>= 1; // halve currentBit
}
}

Marc
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You can use a loop, apparentely you go checking one bit at a time and
depending of its status you add certain value

you should use int instead of ushort for value and doing just a conversion
at the end.

also the C function should work with only minimal changes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top