2010-02-17 32 views

回答

0

因为价值包含您的64位号码

char a1 = (char) (value & 0xffff); 
char a2 = (char) ((value>>16) & 0xffff); 
char a3 = (char) ((value>>32) & 0xffff); 
char a4 = (char) ((value>>48) & 0xffff); 

编辑:添加石膏由评议的建议

+1

字符串在哪里? –

+0

当一个64位的值被复制到一个16位的原语,只有低16位将被复制什么是与0xffff? –

+0

目前还不清楚它们是指字面串还是64位。 – jjnguy

4
String s = someStringOfBits; 
String s0 = someStringOfbits.substring(0, 16); 
String s1 = someStringOfbits.substring(16, 32); 
String s2 = someStringOfbits.substring(32, 48); 
String s3 = someStringOfbits.substring(48, 64); 

这是假设你确实有一个字符串,它类似于此:

1010101010101010101010101010101010101010101010101010101010101010 
3

使用ByteBuffer

ByteBuffer buf = ByteBuffer.allocate(Long.SIZE/Byte.SIZE); 
buf.asLongBuffer().put(0, value); 
short a0 = buf.asShortBuffer().get(0); 
short a1 = buf.asShortBuffer().get(1); 
short a2 = buf.asShortBuffer().get(2); 
short a3 = buf.asShortBuffer().get(3); 
1

这里是做:)不适当的通用方式:

public class MyClass 

{ 

    static public long[] splitIntoNBits(long value, int numBitsPerChunk){  

     long[] retVal = null; 

     if(numBitsPerChunk == 64){ 
      retVal = new long[1]; 
      retVal[0] = value; 
      return retVal; 
     } 

     if(numBitsPerChunk <= 0 || numBitsPerChunk > 64){ 
      return null; 
     } 

     long mask = (1 << numBitsPerChunk) - 1;  
     int numFullChunks = (byte) (64/numBitsPerChunk); 
     int numBitsInLastChunk = (byte) (64 - numFullChunks * numBitsPerChunk); 
     int numTotalChunks = numFullChunks; 
     if(numBitsInLastChunk > 0){ 
      numTotalChunks++; 
     } 

     retVal = new long[numTotalChunks]; 

     for(int i = 0; i < numTotalChunks; i++){ 
      retVal[i] = value & mask; 
      value >>= numBitsPerChunk; 
     } 

     // clean up the last chunk 
     if(numBitsInLastChunk > 0){ 
      mask = (1 << numBitsInLastChunk) - 1; 
      retVal[retVal.length - 1] &= mask; 
     } 

     return retVal; 

    }  




    public static void main(String[] args) 
    {  
     long myvalue = ((long) 0x12345678) | (((long) 0xABCDEF99) << 32);  
     long[] bitFields = splitIntoNBits(myvalue, 16); 
     for(int i=0; i < bitFields.length; i++){ 
      System.out.printf("Field %d: %x\r\n", i, bitFields[i]); 
     } 
    } 
} 

产生输出:

Field 0: 5678 
Field 1: 1234 
Field 2: ef99 
Field 3: abcd 

,并为7 bitsPerField它产生:

Field 0: 78 
Field 1: 2c 
Field 2: 51 
Field 3: 11 
Field 4: 11 
Field 5: 73 
Field 6: 7b 
Field 7: 66 
Field 8: 2b 
Field 9: 1 

这不是很有趣!

相关问题