This discussion is archived
6 Replies Latest reply: Aug 25, 2008 2:34 PM by 843785 RSS

int to byte array

843785 Newbie
Currently Being Moderated
I have an N dimensional byte array. and I have a number 2000 that I would like to fill up to array[10] and array[11]. How do I do that? I know how to do it to a single location but not multiple spread. I think there is a trick to it.
  • 1. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    firewind4000 wrote:
    I have an N dimensional byte array. and I have a number 2000 that I would like to fill up to array[10] and array[11]. How do I do that? I know how to do it to a single location but not multiple spread. I think there is a trick to it.
    A trick to understanding what you wrote here? Try posting a little code.
  • 2. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    byte[] newSet = new byte[150];
    
    public byte[] getCodeInt(int code){
    /*Here is something I need*/
    newSet[10] // conver int 2000 to byte and fill up to location 10
    newSet[11] // and 11
    
    ....
    //a bunch of non-important stuff
    .....
    //finally
    return newSet;
    }
    normally to fill to one location, a simple cast such as newSet[10] = (byte)0xFF; but to multiple location? hint please?
  • 3. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    Here's one way to extract the bytes in an int.
    public static byte[] intToBytes(int x) {
        return new byte[] {
            (byte)(x >> 24),
            (byte)(x >> 16),
            (byte)(x >> 8),
            (byte)(x),
        };
    }
  • 4. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    hey hey it works, thanks doc btw, each byte is between 0 and 255, how come we mask it with by multiple of 8? if you don't mind I ask. obviously it works, so there is a reason for it.
  • 5. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    firewind4000 wrote:
    hey hey it works, thanks doc btw, each byte is between 0 and 255, how come we mask it with by multiple of 8? if you don't mind I ask. obviously it works, so there is a reason for it.
    Are you referring to the expressions like x >> 8? That's bit-shifting, not masking. For example, if x has value 0x20FF8040, then

    (byte)x is byte 0, the low byte (0x40),
    x >> 8 is 0x0020FF80, so (byte)(x>>8) is byte 1, (0x80)
  • 6. Re: int to byte array
    843785 Newbie
    Currently Being Moderated
    yup, thanks that makes sense.