Tuesday, 15 June 2010

int - c# bit shift task with integers -



int - c# bit shift task with integers -

theres exam task , im wondering how solve properly.

task:

we have write output of code solution.

int iq = -99887766; string pout = ""; int mask = 1 << 31; (int n = 1; n <= 32; n++) { pout += (iq & mask) == 0 ? "0" : "1"; iq <<= 1; if (n % 4 == 0) {pout += " ";} } console.writeline(pout);

my suggestions:

first transfer -99887766 binary:

9988776 in binary = 0000 0101 1111 0100 0010 1010 1001 0110

revert bits , add together 1 = 1111 1010 0000 1011 1101 0101 0110 1010

second transfer int mask binary , bitshift (left) 31

mask = 0000 0000 0000 0000 0000 0000 0000 0001

after bitshift = 1000 0000 0000 0000 0000 0000 0000 0000

third in statement, both ints calculated bitwise "&". thats clear me, instance:

(1111 1010 0000 1011 1101 0101 0110 1010 & 1000 0000 0000 0000 0000 0000 0000 0000) != 0 string filled 1.

then bitshift iq 1:

1111 1010 0000 1011 1101 0101 0110 1010 -> 1111 0100 0001 0111 1010 1010 1101 0100

and same operation 1 time again whichs leads 1 stored in string 1 time again , on.

the output @ end should 32 numbers in string 0 or 1 , every 4th number there blank.

is right way solve task?

is there trick faster because giving 10 points meaning should solve within 10 minutes!

what code do? how have named such function? have named so

/// <summary> /// convert int32 value binary string representation. /// </summary> /// <param name="value">the int32 convert.</param> /// <returns>the binary string representation int32 value.</returns> public string convertint32tobinarystring(int32 value) { string pout = ""; int mask = 1 << 31; (int n = 1; n <= 32; n++) { pout += (value & mask) == 0 ? "0" : "1"; value <<= 1; if (n % 4 == 0) {pout += " ";} } homecoming pout; }

the question in exam rephrased "give me binary representation of -99887766 in 32 bit two-complementary code".

there no simple , fast conversion binary 10 minutes quite plenty value below 10 millions. there few methods on paper prefer "descending powers of 2 , subtraction" on "short partition 2 remainder" http://www.wikihow.com/convert-from-decimal-to-binary.

just don't (already having binary representation in sec step) create bit comparisons bit mask.

c# int bit shift

No comments:

Post a Comment