简体   繁体   中英

analysis byte array to class in android or java

The only method i known about ByteArrayInputStream is read() but it just return a integer.

I have a class, and new a variable in someplace. then i store the function's return value in devCfgBytes, How to read it as int short or byte to assign it to the correspond int variable or something else. What should i do? any help is appreciated.

public class ScrewCfg {
    short u16size;
    int u32crc; 
    boolean bEnable;
    byte u8RstFreqDiv;
    final static short screwCfgLegth = 438;
    //...
}
//new obj in someplace
ScrewCfg devCfg = new ScrewCfg();
//....
btnLoadConfig.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        byte[] devCfgBytes = new byte[ScrewCfg.screwCfgLegth];

        int ret = mcLib.ReadUserData(devCfgBytes, ScrewCfg.screwCfgLegth);
        if(ret < 0){
            showMessage("Load Screw configuration Error!");
            return;
        }

        //any method like this? 
        //if i want to read it as boolean, then use one byte
        //read it as integer, then use the four bytes
        ByteArrayInputStream in = new ByteArrayInputStream(devCfgBytes, 1, 1);
        DevCfg.bEnable = in.getBoolean(); 
        in = new ByteArrayInputStream(devCfgBytes, 2, 4);
        DevCfg.u32crc = in.getInt();

    }
}); 

Use DataInputStream

like

in = new DataInputStream(new BufferedInputStream(ByteArrayInputStream(devCfgBytes, 1, 1)));
int anInt = in.readInt();
short aShort = in.readShort();
boolean aBool = in.readBoolean();

then you can use readInt , readShort etc.

http://docs.oracle.com/javase/6/docs/api/java/io/DataInputStream.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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