Wednesday, October 15, 2008

How to convert uchar to ubyte in java

//assume a 16bit value with MSB unsigned
private byte[] encodeUInt8Chars(char[] uchars){

ByteArrayOutputStream stream;
int ui;

stream = new ByteArrayOutputStream();
for(int i=0; i<uchars.length; i++){
ui = uchars[i]&0xFF;    //mask to use the signed bit of int                    
stream.write(ui);
}

return stream.toByteArray();
}

//assume a 8 bit value with MSB being unsigned(was used by the above method)
private char[] decodeUInt8Chars(byte[] uint8){   

CharArrayWriter writer = new CharArrayWriter();
int uc;

for(int i=0; i<uint8.length; i++){
uc = uint8[i]&0xFF;
writer.write(uc);   
}

return writer.toCharArray();
}

No comments:

Post a Comment