When do I have to cast to byte when initialize a byte array in java? -


here code:

import java.io.*;  public class bed {     private string bedfn;     private int bytes_snp;     private int nindiv;     private long bedsize;     private int nsnp;     private byte[] magicbytes;      public bed(string bedfn, int bytes_snp, int nindiv) {         this.bedfn = bedfn;         this.bytes_snp = bytes_snp;         this.nindiv = nindiv;         bedsize = (new file(bedfn)).length();         nsnp = (int) ((bedsize - 3) / bytes_snp);         ///////////////////////////////////////         magicbytes = new byte[] {0x6c, 0x1b, 0x01};     }      //...      public outputstream writebytes(outputstream filestream, byte[] bytes) {         try{             filestream.write(bytes);         } catch (ioexception e) {             e.printstacktrace();         }         return filestream;     }      public outputstream writebytes(outputstream filestream) {         return writebytes(filestream, magicbytes);     }      public outputstream writebytes(string filename, byte[] bytes) throws filenotfoundexception {         fileoutputstream fileoutputstream = new fileoutputstream(filename);         bufferedoutputstream filebufferedoutput = new bufferedoutputstream(fileoutputstream);         return writebytes(filebufferedoutput, bytes);     }       public outputstream writebytes(string filename) throws filenotfoundexception {         return writebytes(filename, magicbytes);     }         public static void main(string[] args) throws ioexception {         string filename = "/users/kaiyin/personal_config_bin_files/workspace/rbed2/inst/extdata/test.bed";         bed bedobj = new bed(filename, 2, 6);          outputstream outputstream = bedobj.writebytes("/tmp/x.bed");         try{             ///////////////////////////////////////             outputstream.write(new byte[] {(byte) 0xff, (byte) 0xff});         } {             outputstream.close();         }      } } 

there 2 byte array initializations (marked ///////), in first didn't cast, in second have to, otherwise error:

error:(194, 45) java: incompatible types: possible lossy conversion int byte 

why?

0xff not fit in range of representable numbers in byte type. maximum value fits in byte 127 0xff represents 255. therefore need cast in case.

when number representable, instance in first case assign 0x6c java compiler accepts without cast after applying narrowing conversion int byte.

when integer value narrowed byte, bits except lowest representable target type discarded. means integer 0xff 00000000000000000000000011111111, lowest 8 bits taken, resuling in byte 11111111 -1. therefore, conversion changed value and sign of initial number.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -