java - Int to byteArray -


i having integer value.now first convert byte array of size 4 following logic :

logic 1

byte[] tempbytes = new byte[4]; int y=1; for(i=3;i>=0;i--){     int sum=0;     for(int j=0;j<8;j++){         int z=x & y;         x=x>>1;         sum=sum+power(2, j)*z;      }     tempbytes[i]=(byte)sum; } 

logic 2 :

    int sizeoffile;     bytearrayoutputstream baos = new bytearrayoutputstream();     dataoutputstream dos = new dataoutputstream(baos);     dos.writeint(sizeoffile);     dos.close();     byte[] tempbytes = baos.tobytearray(); 

now array may contain negative values if int value 8401 corresponding byte array 0 0 32 -47.

i convert byte array string s doing :

s=new string(temp); 

i convert string bytes using getbytes().

but result gives 0 0 32 -17.so when convert int gives wrong result. here sizefile bytearray after convert string bytes again.

int sizeoffilerecieved = java.nio.bytebuffer.wrap(sizefile).getint(); 

what can problem here.please how solve it.

assuming convertion int byte array correct, negative bytes normal because that's decimal representation, it's not error. if byte value on 127, msb 1, java means negative number. in java there's no unsigned values, if show decimal representation show negative. if want see byte value unsigned can convert hex representation (integer.tohexstring), or use bigger holder short or int see unsigned decimal value.

the point here byte value always same, can show in different ways (signed, unsigned, hexadecimal, etc..). value representation can confuse you. value , representation 2 different things.

also might want bit shifting instead of using powers, way slower.


Comments

Popular posts from this blog

javascript - Unusual behaviour when drawing lots of images onto a large canvas -

how can i manage url using .htaccess in php? -

ios - I get the error Property '...' not found on object of type '...' -