Converting an integer to a byte array?

I have a checksum calculation and i stor it into an int. but when i saved to my test.dat file this number showd up as 05 in hex, which is only 1 byte out of 4 that is displayed. I have been looking around and playin and stuff but havent found anything helpful.
checksum(4 bytes) : 2126934821
// Stream access
FileInputStream fischar;
FileOutputStream outchar;
// CS byte array
byte [] orgCS = new byte[4];
//byte [] bnewCS = new byte[4];
int newCS;
public void writecss() {
System.out.print( "New checksum(" + 4 + " bytes) : "+newCS+"\n" );
try{
// writing original checksum and new checksum into a .dat file spaced with a zero
outchar = new FileOutputStream( fcs );
outchar.write(orgCS); // byte array being written
outchar.write(0);
outchar.write(0);
outchar.write(newCS); // Int being written
outchar.close();
System.exit(0);
}catch(IOException ioe){
// Print IO error
System.out.print( ioe );
System.exit(0);
the output is so
FD6E 945E 0000 F3 : .n.^...
you can see where the 2 zero bytes act like a spacer, and you see the integer being cut off for some reason. o_O can you help me out?

Not sure if this help you?
     * Writes the specified byte to this output stream. The general
     * contract for <code>write</code> is that one byte is written
     * to the output stream. The byte to be written is the eight
     * low-order bits of the argument <code>b</code>. The 24
     * high-order bits of <code>b</code> are ignored.
     * <p>
     * Subclasses of <code>OutputStream</code> must provide an
     * implementation for this method.
     * @param      b   the <code>byte</code>.
     * @exception  IOException  if an I/O error occurs. In particular,
     *             an <code>IOException</code> may be thrown if the
     *             output stream has been closed.
    public void write(int b) throws IOException
     * Writes <code>b.length</code> bytes from the specified byte array
     * to this output stream. The general contract for <code>write(b)</code>
     * is that it should have exactly the same effect as the call
     * <code>write(b, 0, b.length)</code>.
     * @param      b   the data.
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.OutputStream#write(byte[], int, int)
    public void write(byte b[]) throws IOException Extract from OutputStream API

Similar Messages

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • How to convert a Image object to byte Array?

    Who can tell me, how to convert Image object to byte Array?
    Example:
    public byte[] convertImage(Image img) {
    byte[] b = new byte...........
    return b;

    Hello,
    any way would suit me, I just need a way to convert Image or BufferedImage to a byte[], so that I can save them. Actually I need to save both jpg and gif files without using any 3rd party classes. Please help me out.
    thanx and best wishes

  • Question on converting an int to 4 byte array

    Hello all. I apologize in advance if this information is readily available, because I haven't been able to find a definitive answer to this question. I need to convert an int to a big endian 4 byte-array. I have the following code, which I'm fairly sure works, but it's the big endian part I'm not sure about. Can anyone confirm that this code snippet will do what I expect:
    public static final byte[] intToByteArray(int value)
        return new byte[]
            (byte)(value & 0xff),
            (byte)(value >> 8 & 0xff),
            (byte)(value >> 16 & 0xff),
            (byte)(value >>> 24) };
    }Thank you very much in advance for your help.
    -Kennedy

    kook04 wrote:
    Hello all. I apologize in advance if this information is readily available, because I haven't been able to find a definitive answer to this question. I need to convert an int to a big endian 4 byte-array. I have the following code, which I'm fairly sure works, but it's the big endian part I'm not sure about. Can anyone confirm that this code snippet will do what I expect:The best way is to test it for yourself.
    int i = 0xAABBCCDD;
    byte[] bytes = intToByteArray(i);
    if (bytes[0] == (byte)0xAA && bytes[1] ... etc.) {
      System.out.println("Success!");
    else {
      System.out.println("Oops!")
    }

  • How to convert the record stored iin byte array to integers

    im making a simple game in j2me and i want to get the max scores and show it for each player , what i face right now that i cant convert the records which i stored in bytes to integers when i read it from file to get the max.
    thanks

    have a look at java.io.DataInputStream

  • How to convert  Wav file  in to byte array an vise vers into RMS???????????

    hi Constantinos Loizou
    i m having same problem which u were facing in last month.
    my problem i have to save .WAV file into RMS and then retreive it from RMS.
    my Code is
    Read From RMS
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    if(rsUser.getNumRecords() > 0)
    try {
    byte[] byusrinfo = rsUser.getRecord(1);
    InputStream in = new ByteArrayInputStream(byusrinfo,0,byusrinfo.length);
    p = Manager.createPlayer(in,"audio/x-wav");
    p.start();
    return true;
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    Write in RMS
    try {
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    int idata = is.available();
    byte[] exdata = new byte[idata];
    is.read(exdata);
    if(rsUser.getNumRecords() > 0) {
    rsUser.setRecord(1,exdata,0,exdata.length);
    else {
    rsUser.addRecord(exdata,0,exdata.length);
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace ();
    now i have the file successfully when i retrieve it from RMS and p.reliaze() give me exception
    javax.microedition.media.MediaException: Failed to realize Player: Malformed wave media: expected 'RIFF'
    have u able to solve it. if yes then pls give me solution. or give other solution if this soution is not good
    regardz
    Hassan Mushtaq

    Well, I'm not going to give you your code on a silver platter. You'll need to put some effort in it yourself.
    So look at that available() method yourself an see if you can improve on that. Look at the api docs, there is loads of information there, and often it will give you pointers on why things are not working.

  • Convert float to 4 bytes array

    How can I convert float type to 4 byte array -
    not with strings but to exact binary representation.

    See the javadoc of Float.floatToIntBits. Converting an int to an array of 4 bytes is easy, so I will left it as an exercise.
    floatToIntBits
    public static int floatToIntBits(float value)Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.
    Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
    If the argument is positive infinity, the result is 0x7f800000.
    If the argument is negative infinity, the result is 0xff800000.
    If the argument is NaN, the result is 0x7fc00000.
    In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).
    Parameters:
    value - a floating-point number.
    Returns:
    the bits that represent the floating-point number.

  • Reading in any file and converting to a byte array

    Okay what I am trying to do is to write a program that will read in any file and convert it into a int array so that I can then manipulate the values of the int array and then re-write the file. Once I get the file into an int array I want to try and compress the data with my own algorithm as well as try to write my own encryption algorithm.
    What I have been looking for is code samples that essentially read in the file as a byte array and then I have been trying to convert that byte array into an int array which I could then manipulate. So does anyone have any sample code that essentially takes a file and converts it into an int array and then converts it back into a byte array and write the file. I have found code that is close but I guess I am just too new to this. Any help would be appreciated.

    You can read a whole file into a byte array like this:File f = new File("somefile");
    int size = (int) f.length();
    byte[] contents = new byte[size];
    DataInputStream in = new DataInputStream(
                              new BufferedInputStream(new FileInputStream(f)));
    in.readFully(contents);
    in.close();Note that you need to add in the proper exception handling code. You could also use RandomAccessFile instead of the DataInputStream.
    Writing a byte array to a file is easier; just construct the FileOutputStream, call write on it with the byte array, and close the stream.

  • Converting Image to Byte Array and then to String

    Hi All...
    Can anyone please help me. I have got a problem while converting a Byte array of BufferedImage to String.
    This is my code, First i convert a BufferedImage to a byte array using ImageIO.wirte
    public String dirName="C:\\image";
    ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
    BufferedImage img=ImageIO.read(new File(dirName,"red.jpg"));
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] resultimage=baos.toByteArray();
    baos.close();
    Then i tried to convert this byte array to a string
    String str=new String(resultimage);
    byte[] b=str.getBytes();
    This much worked fine. But when i reversed this process to re-create the image from that string. i found the image distroted.
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(b));
    ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    I got this snap.jpg as distroted.
    Please help me i have to convert the image to a string and again i have to re-create the image from that string.

    To conver the bytearray to string use base64.encoding
    String base64String= Base64.encode(baos.toByteArray());
    To convert back use Base64.decode;
    byte[] bytearray = Base64.decode(base64String);
    BufferedImage imag=ImageIO.read(bytearray);

  • How do i covert an image in J2ME into an byte array ?

    Can anyone help to show me the way to convert an image into a byte array ?
    Thanks early reply appreciated.

    Hi! I�m developing an application to be installed in two devices. My problem is that i want to send an image: I can receive it with createImage(InputStream ip), but how can i send it with OutputStream? it needs a byte array (method write), how can i convert an image into a byte array?is there any other solution? like send it as a string...
    Thanks

  • Byte array in JSON reply

    Hi guys,
    I'm exchanging some data between .net webservice and flex
    with JSON. This is a JSON reply:
    <string>
    {"uid":"23","photos":[[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,72,0,72,0,0,255,219,0,67 ,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,20
    </string>
    It is serialized this class:
    public class UserPhotoBytes
    public string uid;
    public ArrayList photos;
    public UserPhotoBytes()
    Where photos is THE ARRAY OF BYTE ARRAYS. Then in Flex I
    deserialize it with:
    public function
    onPhotoReceived(event:GetUserPhotoResultEvent):void
    var myImg:Image = new Image();
    var rawData:String = String(event.result);
    var userPhoto:Object = JSON.decode(rawData) as Object
    _user.photos = userPhoto.photos as Array;
    myImg.data = _user.photos[0] as ByteArray;
    But I think it cannot convert the string value of byte array
    of JSON object to real byte representation. Or am I missing
    something else ? Thank you very much for the response

    Hi,
    I am opening the file with wordpad.
    when opening the file the output i could see is:
    U
    wU
    w
    which is ASCII value I guess. Pls tell me if my guess is wrong & value is in binary format only.I am somewhat confused :O.
    As per the client requirement he should get the value in the file as binary format and not as ASCII.
    I hope i am not misleading you and hope that now you got what is my problem.
    Neha

  • Object stream and byte array conversion

    Hello everyone,
    I am wondeirng how to convert an ObjectInputStream to a byte array, then convert the array back to ObjectInputStream -- should I convert the array back to ObjectOutputStream other than ObjectInputStream?
    Any sample codes?
    thanks in advance,
    George

    Isn't it the other way around? You can't do this directly:
    ObjectInputStream ois = ...;
    ByteArrayInputStream bais = new ByteArrayInputStream(ois);(but you can do it indirectly), but you can do this:
    ByteArrayInputStream bais = ...;
    ObjectInputStream ois = new ObjectInputStream(bais);

  • How to convert an Integer to byte[] without lose data?

    How to convert an Integer to byte[] without lose data?

    I use the following to convert any java Object to a byte array
    public static byte[] getBytes(Object obj) throws java.io.IOException
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            bos.close();
            byte [] data = bos.toByteArray();
            return data;
    }

  • Converting image into byte array

    Hi all,
    How to convert an integer array image into byte array ?
    here i have a image like this :
    private static int pixelArray[] = {
    0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
    From this one i create image like this one :
    Image image = Image.createRGBImage(pixelArray, width, height, true);
    Now i want to convert that pixelArray into byte array ? how to do this
    additionally i want to send this byte array to servlet .
    thanks in advance.

    Hi,
    If you want to convert your int array to a byte array you should
    split each integer into 4 bytes to avoid losing information. You can
    rebuild your integer array later if you need to. I think this code
    will work (i havent tested it):
    byte[] pixel= new byte[pixelArray.length<< 2];
    for (int i= pixelArray.length- 1; i>= 0; i--) {
      int aux= i<< 2;  // i* 4 = i<< 2
      pixel[aux]=    (byte) (pixelArray>> 32);
    pixel[aux+ 1]= (byte) (pixelArray[i]>>> 16);
    pixel[aux+ 2]= (byte) (pixelArray[i]>>> 8);
    pixel[aux+ 3]= (byte) pixelArray[i];
    Greets.

  • What is the best way to convert a cluster into byte array or string

    I'm writing a program that sends UDP packets and I've defined the data I want to send via large clusters (with u8/u16/u32 numbers, u8/u16/u32 arrays, and nested clusters). Right before sending the data, I need to convert the clusters either into strings or byte arrays. The flatten to string function is almost perfect for this purpose. However, it's appending lengths to arrays and strings which renders this method useless, as far as I can tell. 
    As I have many of these clusters, I would rather not hard code the unbundle by names and converting/typecasting to byte arrays or strings for each one. 
    Is there a feature or tool I am overlooking? 
    Thank you! 

    deceased wrote:
    Flatten to string has a boolean input of "Prepend string or array size" ... The default value is true.
    That only specifies if a string or array size should be prepended if the outermost data element is a string or array. For embedded strings or arrays it has no influence. This is needed for the Unflatten to be able to reconstruct the size of the embedded strings and arrays.
    The choice to represent the "Strings" (and Arrays) in the external protocol to LabVIEW strings (and arrays) is actually a pretty bad one unless there is some other element in the cluster that does define the length of the string. An external protocol always needs some means to determine how long the embedded string or array would be in order to decode the subsequent elements that follow correctly.
    Possible choices here are therefore:
    1) some explicit length in the protocol (usually prepended to the actual string or array)
    2) a terminating NULL character for strings, (not very friendly for reliable protocol parsing)
    3) A fixed size array or string
    For number 1) and 2) you would always need to do some special processing unless the protocol happens to use explicitedly 32 bit integer length indicators directly prepended before the variable sized that.
    For number 3) the best representation in LabVIEW is actually a cluster with as many elements inside as the fixed size.
     

Maybe you are looking for

  • Win7 - Audigy 2 ZS - CMSS

    Win7 - Audigy 2 ZS - CMSS7 Hello everyone, Before you all start thinking, ohh he just registered to get what he wanted, yes your right, thats what i have done. I installed Windows 7 Ultimate 32-bit on my computer today, before installing Windows 7 i

  • Cover Flow annoyance

    Cover Flow is cool. It lets you get to music quicker and looks pretty. But I'm over it. I want to turn it off. I'm and sick and tired of it switching to cover flow when i don't want it too. Prime example is when you are lying down - You put the ipod

  • Query with Cost Center Hierarchy giving incorrect results

    Hi All, I have a universe built based on BEx query on Cost Center cubes. When enabling hierarchy in BEx Query and building Web intelligence Report based on the universe, I get incorrect results.  The levels of the hierarchy is incorrect, many of the

  • Wht is similar field of BDC's BBKPF-BVORG in BAPI-BAPI_ACC_DOCUMENT_POST?

    Hi Experts, We can post GL acct docs via BDC and BAPI (BAPI_ACC_DOCUMENT_POST). In BDC, there is a filed w/ name BBKPF-BVORG-->Number of Cross-Company Code Posting Transaction, so, I am lookig for the same field/any other similar to BVPRG, in BAPI st

  • Client Independent & client dependent tables

    Hello, Can anyone please tell me what is client dependent and client independent tables? Thanks in advance. Regards Srini