Is there a nice way to split an int into two shorts (.NET)?

前端 未结 13 1817
情深已故
情深已故 2021-01-01 11:25

I think that this is not possible because Int32 has 1 bit sign and have 31 bit of numeric information and Int16 has 1 bit sign and 15 bit of numeric information

13条回答
  •  渐次进展
    2021-01-01 11:55

    yes it can be done using masking and bitshifts

     Int16 a,b;
     Int32 c;
    
     a = (Int16) (c&0xffff);
     b = (Int16) ((c>>16)&0xffff);
    

    EDIT

    to answer the comment. Reconstructionworks fine:

     Int16 a, b;
     Int32 c = -1;
    
     a = (Int16)(c & 0xffff);
     b = (Int16)((c >> 16) & 0xffff);
    
     Int32 reconst = (((Int32)a)&0xffff) | ((Int32)b << 16);
    
     Console.WriteLine("reconst = " + reconst);
    

    Tested it and it prints -1 as expected.

    EDIT2: changed the reconstruction. The promotion of the Int16 to Int32 caused all sign bits to extend. Forgot that, it had to be AND'ed.

提交回复
热议问题