简体   繁体   English

ByteBuffer-将long转换为char数组,反之亦然

[英]ByteBuffer - convert long to char array and vice versa

I am trying to convert a long to a 4 char array. 我正在尝试将long转换为4个字符的数组。

It seems like the last char is not being written to the buffer. 似乎最后一个字符没有被写入缓冲区。

Why is this not working? 为什么这不起作用?

//convert long to char array

long longValZ = 219902744986400000L;

ByteBuffer bbX = ByteBuffer.allocate(8);
bbX.putLong(longValZ); 
//longValZ = 219902744986400000

char [] charArr1 = new char[4];
charArr1[0] = bbX.getChar(0);
charArr1[1] = bbX.getChar(1);
charArr1[2] = bbX.getChar(2);
charArr1[3] = bbX.getChar(3);

long longValX = bbX.getLong(0); 
//longValX = 219902744986400000


//convert char array to long

ByteBuffer bbY = ByteBuffer.allocate(8);

bbY.putChar(0,charArr1[0]);
bbY.putChar(1,charArr1[1]);
bbY.putChar(2,charArr1[2]);
bbY.putChar(3,charArr1[3]);

long longValY = bbY.getLong(0); 
//longValY = 219902744985600000 --> why is longValY different than longValZ ?

Thanks to Sotirios, here is the correct answer: 感谢Sotirios,这是正确的答案:

//convert long to char array

long longValZ = 219902744986400000L;

ByteBuffer bbX = ByteBuffer.allocate(8);
bbX.putLong(longValZ); 

char [] charArr1 = new char[4];
charArr1[0] = bbX.getChar(0);
charArr1[1] = bbX.getChar(2);
charArr1[2] = bbX.getChar(4);
charArr1[3] = bbX.getChar(6);



//convert char array to long

ByteBuffer bbY = ByteBuffer.allocate(8);
bbY.putChar(0,charArr1[0]);
bbY.putChar(2,charArr1[1]);
bbY.putChar(4,charArr1[2]);
bbY.putChar(6,charArr1[3]);

long longValY = bbY.getLong(0); 

You don't need to provide the index 您不需要提供索引

long longValZ = 219902744986400000L;

ByteBuffer bbX = ByteBuffer.allocate(8);
bbX.putLong(longValZ); 

char[] charArr1 = new char[4];
for (int i = 0; i < charArr1.length; i++)
   charArr1[i] = bbX.getChar();



//convert char array to long

ByteBuffer bbY = ByteBuffer.allocate(8);
for (int i = 0; i < charArr1.length; i++)
    bbY.putChar(charArr1[i]);

long longValY = bbY.getLong(0); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM