2010-02-17 6 views

Répondre

0

étant donné que la valeur contient votre numéro de 64bit

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

modifier: moulages ajouté comme suggéré par commentateur

+1

où est la chaîne? –

+0

lorsqu'une valeur 64 bits est copiée sur une primitive 16 bits et que seuls les 16 bits inférieurs seront copiés quel est le point dans et avec 0xffff? –

+0

Il n'est pas clair si elles signifient littéralement 'String' ou seulement 64 bits. – 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); 

Ceci est en supposant que vous avez en fait une chaîne qui ressemble à ceci:

1010101010101010101010101010101010101010101010101010101010101010 
3

Utilisation d'un 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

est ici une façon inappropriée générique de le faire :):

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]); 
     } 
    } 
} 

produit sortie:

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

et pour une bitsPerField de 7, il produit:

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 

N'est-ce pas amusant?

Questions connexes