Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

Caused by: java.lang.StringIndexOutOfBoundsException: length=7; index=7 Android java

Hi i use function to hex string to byte array and it gives me this error sometimes it works some times it gives error

Caused by: java.lang.StringIndexOutOfBoundsException: length=7;index=7 > at java.lang.String.indexAndLength(String.java:500) at java.lang.String.charAt(String.java:494)

public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len/2];

        for(int i = 0; i < len; i+=2){
            data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
         }

        return data;
    }

error comes in this code and why it works most of the time and only sometimes it makes application force close,can anybody fix this so that it can work always

i use this function above to make crc32 checsum to bytearray

here is the function i use to get crc32 checsum

private String chesum() {

        String fileName = "file.bin";

        try {

            CheckedInputStream cis = null;

            try {
                // Compute CRC32 checksum
                cis = new CheckedInputStream(
                        new FileInputStream(fileName), new CRC32());

            } catch (FileNotFoundException e) {
                System.err.println("File not found.");

            }

            byte[] buf = new byte[128];
            while(cis.read(buf) >= 0) {
            }

            long checksum = cis.getChecksum().getValue();

            String ss = Long.toHexString(checksum);

            cis.close();
            return ss;

        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;


    }

after this method i call hexstringtobytearray function

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
for(int i = 0; i < len-1 ; i+=2){
            data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
         }

Change the condition len to len -1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...