如何在Java中将64位字符串分成4位16位?

时间:2010-02-17 19:25:37

标签: java bit-manipulation

如何将64位输入分成16位?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分: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

并且对于bitsPerField为7,它产生:

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

不是很有趣!?

答案 3 :(得分: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);

编辑:按照评论者的建议添加演员