【问题标题】:Byte buffer exception for strings of length less than 4长度小于 4 的字符串的字节缓冲区异常
【发布时间】:2013-01-23 20:19:18
【问题描述】:

我正在尝试使用 ByteBuffer (java.nio.ByteBuffer) 将字符串转换为其整数等价物以便更快地进行比较。

我在使用ByteBuffer 时遇到了一个非常特殊的异常。

public class LargeCompare {

    public static void main(String args[]){
        byte[]b ="zzz".getBytes();
        ByteBuffer bb = ByteBuffer.wrap(b);
        bb.getInt();
    }
}

上述代码不会为长度为 4 的字符串引发异常,但会为长度为 3 及以下的字符串引发异常。

谁能帮我解决这个问题?

【问题讨论】:

    标签: java string bytebuffer


    【解决方案1】:

    int 是 32 位或 4 字节宽。您正在尝试从比这更短的缓冲区中读取int。这就是您收到异常的原因。

    我不太了解你的想法,所以不会提出建议。

    【讨论】:

      【解决方案2】:

      嗯,来自文档:

      抛出: BufferUnderflowException - 如果此缓冲区中剩余的字节少于四个

      你只有 3 个字节。

      【讨论】:

        【解决方案3】:

        这里是解决方案...

        public class LargeCompare {
        
        public static void main(String args[]){
            String str = "A";
            System.out.println(bytesToInt(str.getBytes()));
        }
        
        public static int bytesToInt(byte[] byteArray){          
            int value= 0;
            for(int i=0;i<byteArray.length;i++){                
            int x=(byteArray[i]<0?(int)byteArray[i]+256:(int)byteArray[i])<<(8*i);             
                value+=x;
            }         
            return value;       
        }}
        

        我已经测试了这段代码,没有任何问题......

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-08-02
          • 2014-12-31
          • 2022-01-20
          • 1970-01-01
          • 2010-12-18
          • 1970-01-01
          相关资源
          最近更新 更多