Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
改进Java中的字节转换_Java - Fatal编程技术网

改进Java中的字节转换

改进Java中的字节转换,java,Java,我需要一些帮助来改进下面的代码-字节和int之间有一个转换,这在所有情况下都不起作用-我需要一些反馈来发现和解决可能涉及BytePoint IntToByte转换的问题 int start = 02; int stepSize = 256; int bytesLeftToRead = // [0][1] encode a hex value as two bytes // this part only works for [0] > 0 and [0] < 10 -- other

我需要一些帮助来改进下面的代码-字节和int之间有一个转换,这在所有情况下都不起作用-我需要一些反馈来发现和解决可能涉及BytePoint IntToByte转换的问题

int start = 02;
int stepSize = 256;
int bytesLeftToRead = 
// [0][1] encode a hex value as two bytes
// this part only works for [0] > 0 and [0] < 10 -- other restrictions?
response[0]*256 + Integer.parseInt(Integer.toHexString(response[1] + 256), 16);

while(bytesLeftToRead > 0){

    // convert where to start from int to two bytes
    cmdReadPD[2] = (byte) (start / 256);
    cmdReadPD[3] = (byte) (start % 256);

    if(stepSize > bytesLeftToRead){
        stepSize = bytesLeftToRead;
    }

    // encode stepsize in two bytes
    cmdReadPD[5] = (byte) (stepSize / 256);
    cmdReadPD[6] = (byte) (stepSize % 256);

    start += stepSize;
    bytesLeftToRead -= stepSize;
    read(cmdReadPD, stepSize);
}
int start=02;
int步长=256;
int bytesleeftoread=
//[0][1]将十六进制值编码为两个字节
//此部分仅适用于[0]>0和[0]<10--其他限制?
响应[0]*256+整数.parseInt(整数.toHexString(响应[1]+256]),16);
while(bytesleeftoread>0){
//将起始位置从int转换为两个字节
cmdReadPD[2]=(字节)(开始/256);
cmdReadPD[3]=(字节)(开始%256);
如果(步长>字节左读){
步长=bytesleeftoread;
}
//将步长编码为两个字节
cmdReadPD[5]=(字节)(步长/256);
cmdReadPD[6]=(字节)(步长%256);
开始+=步长;
bytesLeftToRead-=步长;
读取(cmdReadPD,步长);
}
使用
(字节)((开始>>8)和0xFF)
(字节)(开始和0xFF)

请注意,它只对小于2^16的整数有帮助


要将字节重新提取为int,请使用
(lo&0xFF)|((hi&0xFF)我将使用ByteBuffer读取和写入短(有符号)或字符(无符号)值


在您的代码中,Integer.parseInt(Integer.toHexString(response[1]+256),16)是什么对十六进制数的前两位进行编码-因为字节可以是负数,所以我必须加256-然后我使用toHexString将int值转换为hexString,并使用parseInt获得该hexString的整数值这太复杂了。请参见我的回答,
((响应[0]&0xFF))刚刚注意到您忘记了一些括号!它实际上是((hi&0xFF)
ByteBuffer response = ByteBuffer.allocate(8);// .order(ByteOrder.LITTLE_ENDIAN);  if you need to change it.
ByteBuffer cmdReadPD = ByteBuffer.allocate(8);

int reponseCode = response.getChar(0);

while(cmdReadPD.remaining() > 0){
    // convert where to start from int to two bytes
    cmdReadPD.setshort(2, (short) start);

    if(stepSize > bytesLeftToRead)
        stepSize = bytesLeftToRead;

    // encode stepsize in two bytes
    cmdReadPD.setshort(4, (short) stepSize);