Casting int to a byte -- retreiving the lowest 8 bits

Yo, thought i'd try to open up some debate on this topic. I wrote a data feed that needed to grab the lower 8 bits out of an int, so i wrote what i believed to be the standard way of doing this, which was effectively
public static byte intToByte( int c ) {
        return (byte) (c & 0xff);
}A colleague looking through my code asked whether the & 0xff was necessary, and did i believe that there was any value of c for which it made a difference, as he believed that this was equivalent to just
return (byte)c; My immediate thought was worrying about byte in java being signed, and having data screwed up, so i ran some tests.. and on every value i tried (byte)c is indeed equivalent to (byte)( c & 0xff ).
My argument was to be that (byte)( c & 0xFF ); is great code to read as a maintainer, because it;'s immediately obvious that you are strictly interested in the lowest 8 bits of the int, and nothing else is of importance, and a simple (byte)c; can look naive and make every developer looking at the code for the first time think it's incorrect.
However, i knew his comeback would be that the datafeed has an overriding need for speed, so i ran some tests comparing the repeated operation of (byte)c to (byte)(c & 0xff ) over a range of 100,000 numbers (test repeated several times to obviate startup times). It turned out that doing the & 0xff added about 30% to execution time on my machine (java 1.5 on WinXP). That's quite a severe penalty for a very common operation! I think i'm going to change the code to cast straight to a byte and leave a big comment beforehand explaining how it's equivalent to (byte)(c & 0xff );
This got me wondering how it was implemented in the core java libraries though, since OutputStream has a method to write a byte that actually takes an int parameter. How does this work? Most of the lowest level OutputStream implementations seem to end up going to native to do this (understandably), so i dug out ByteArrayOutputStream. This class does optimise away the & 0xFF and is roughly
    public synchronized void write(int b) {
            �
            buf[count] = (byte)b;
            �
    }No problems with that, so writing to these babies will be fast. But then i started wondering about the methods of DataOutputStream, which is heavily used by use for serialising (a great deal of) internal data flow. Unfortunately in this class there are a lot of redundant & 0xFFs:
public final void writeShort(int v) throws IOException {
        out.write((v >>> 8) & 0xFF);
        out.write((v >>> 0) & 0xFF);
        incCount(2);
public final void writeInt(int v) throws IOException {
      out.write((v >>> 24) & 0xFF);
      out.write((v >>> 16) & 0xFF);
      out.write((v >>>  8) & 0xFF);
      out.write((v >>>  0) & 0xFF);
      incCount(4);
}[The v >>> 0 seems to be optimised out at runtime and i get no execution time difference between ( v >>> 0)  & 0xff that and ( v & 0xff ) so i got no problems with that]
which again seems ok on inspection because the code looks tidy and clean and easy to understand, but i need to hit these things very heavily so would rather they were 30% faster than easy to read. Interestingly they've taken an entirely different approach for writing out a long value:
public final void writeLong(long v) throws IOException {
        writeBuffer[0] = (byte)(v >>> 56);
        writeBuffer[1] = (byte)(v >>> 48);
        writeBuffer[2] = (byte)(v >>> 40);
        writeBuffer[3] = (byte)(v >>> 32);
        writeBuffer[4] = (byte)(v >>> 24);
        writeBuffer[5] = (byte)(v >>> 16);
        writeBuffer[6] = (byte)(v >>>  8);
        writeBuffer[7] = (byte)(v >>>  0);
        out.write(writeBuffer, 0, 8);
        incCount(8);
}both using a private buffer field for the writing before squirting it all out, and not bothering to mask the lower 8 bits. It seems strange that writeLong appears optimised, but writeInt and writeShort are not.
What does everyone else think? Are there any other heavy users of DataOutputStream out there that would rather have things written faster? I guess i'm going to be writing my own version of DataOutputStream in the meantime, because we're writing so much data over these and i'm in an industry where milliseconds matter.

To my knowledge, in your situation, the & 0xFF is not necessary. I believe that the most common use of the mask in this case is actually to treat the lower 8 bits as an unsigned integer. For example:
int value = 65530;
int anotherValue = value & 0xFF; // anotherValue == 250Anyway, the case space is small enough that I just brute forced your problem. Under v1.5.0_07 on Linux, (byte)i and (btye)(i & 0xFF) are definitely the same:
for (int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++)
    byte a = (byte)i;
    byte b = (byte)(i & 0xFF);
    if (a!=b) System.out.println(i);
byte a = (byte)(Integer.MAX_VALUE);
byte b = (byte)(Integer.MAX_VALUE & 0xFF);
if (a!=b) System.out.println(Integer.MAX_VALUE);Perhaps the & 0xFF was in response to some older bug or other behavior.

Similar Messages

  • Trying to understand the details of converting an int to a byte[] and back

    I found the following code to convert ints into bytes and wanted to understand it better:
    public static final byte[] intToByteArray(int value) {
    return new byte[]{
    (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
    }I understand that an int requires 4 bytes and that each byte allows for a power of 8. But, sadly, I can't figure out how to directly translate the code above? Can someone recommend a site that explains the following:
    1. >>> and >>
    2. Oxff.
    3. Masks vs. casts.
    thanks so much.

    By the way, people often introduce this redundancy (as in your example above):
    (byte)(i >> 8 & 0xFF)When this suffices:
    (byte)(i >> 8)Since by [JLS 5.1.3|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363] :
    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.Casting to a byte is merely keeping only the lower order 8 bits, and (anything & 0xFF) is simply clearing all but the lower order 8 bits. So it's redundant. Or I could just show you the more simple proof: try absolutely every value of int as an input and see if they ever differ:
       public static void main(String[] args) {
          for ( int i = Integer.MIN_VALUE;; i++ ) {
             if ( i % 100000000 == 0 ) {
                //report progress
                System.out.println("i=" + i);
             if ( (byte)(i >> 8 & 0xff) != (byte)(i >> 8) ) {
                System.out.println("ANOMOLY: " + i);
             if ( i == Integer.MAX_VALUE ) {
                break;
       }Needless to say, they don't ever differ. Where masking does matter is when you're widening (say from a byte to an int):
       public static void main(String[] args) {
          byte b = -1;
          int i = b;
          int j = b & 0xFF;
          System.out.println("i: " + i + " j: " + j);
       }That's because bytes are signed, and when you widen a signed negative integer to a wider integer, you get 1s in the higher bits, not 0s due to sign-extension. See [http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]
    Edited by: endasil on 3-Dec-2009 4:53 PM

  • Is there a command to display the lowest int?

    What I need is a to find the lowest value for a given amount of integers.
    For example. Say I have 4,5,3,1,2 I want to beable to pick out the smallest value, also can I have the same for the largest.
    Thanks and all the best :o)

    Oh come on people! Just loop the array looking for the min. "Copy the array, then sort it"?!?!
    Sorry for the rant, but that's using dynamite when a hammer will do, and there really is no excuse - doing it "right" is so simple...
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < myArray.length; i++){
       if (myArray[i] < min) min = myArray;
    QED.
    - K

  • Most efficient way to write 4 bytes at the start of any file.

    Quick question: I want to write 4 bytes at the start of a file without overriding the current bytes in the file. E.g. push bytes 0-4 along... Is my only option writing the bytes into a new file then writing the rest of the file after? RAF is so close but overrides :(.
    Thanks Mel

    I revised the code to use a max of 8MB buffers for both the nio and stdio copies...
    Looks like NIO is a pretty clear winner... but your milage may vary, lots... you'd need to test this 100's of times, and normalize, to get any "real" metrics... and I for one couldn't be bothered... it's one of those things that's "fast enough"... 7 seconds to copy a 250 MB file to/from the same physical disk is pretty-effin-awesome really, isn't it? ... looks like Vista must be one of those O/S's (mentioned in the API doco) which can channel from a-to-b without going through the VM.
    ... and BTW, it took the program which produced this file 11,416 millis to write it (from an int-array (i.e. all in memory)).
    revised code
    package forums;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.channels.FileChannel;
    class NioBenchmark1
      private static final double NANOS = Math.pow(10,9);
      private static final int BUFF_SIZE = 8 * 1024 * 1024; // 8
      interface Copier {
        public void copy(File source, File dest) throws IOException;
      static class NioCopier implements Copier {
        public void copy(File source, File dest) throws IOException {
          FileChannel in = null;
          FileChannel out = null;
          try {
            in = (new FileInputStream(source)).getChannel();
            out = (new FileOutputStream(dest)).getChannel();
            final int buff_size = Math.min((int)source.length(),BUFF_SIZE);
            long n = -1;
            int pos = 0;
            while ( (n=in.transferTo(pos, buff_size, out)) == buff_size ) {
              pos += n;
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      static class NioCopier2 implements Copier {
        public void copy(File source, File dest) throws IOException {
          if ( !dest.exists() ) {
            dest.createNewFile();
          FileChannel in = null;
          FileChannel out = null;
          try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            final int buff_size = Math.min((int)in.size(),BUFF_SIZE);
            long n = -1;
            int pos = 0;
            while ( (n=out.transferFrom(in, 0, buff_size)) == buff_size ) {
              pos += n;
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      static class IoCopier implements Copier {
        private byte[] buffer = new byte[BUFF_SIZE];
        public void copy(File source, File dest) throws IOException {
          InputStream in = null;
          FileOutputStream out = null;
          try {
            in = new FileInputStream(source);
            out = new FileOutputStream(dest);
            int count = -1;
            while ( (count=in.read(buffer)) != -1) {
              out.write(buffer, 0, count);
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      public static void main(String[] arg) {
        final String filename = "SieveOfEratosthenesTest.txt";
        //final String filename = "PrimeTester_SieveOfPrometheuzz.txt";
        final File src = new File(filename);
        System.out.println("copying "+filename+" "+src.length()+" bytes");
        final File dest = new File(filename+".bak");
        try {
          time(new IoCopier(), src, dest);
          time(new NioCopier(), src, dest);
          time(new NioCopier2(), src, dest);
        } catch (Exception e) {
          e.printStackTrace();
      private static void time(Copier copier, File src, File dest) throws IOException {
        System.gc();
        try{Thread.sleep(1);}catch(InterruptedException e){}
        dest.delete();
        long start = System.nanoTime();
        copier.copy(src, dest);
        long stop = System.nanoTime();
        System.out.println(copier.getClass().getName()+" took "+((stop-start)/NANOS)+" seconds");
    output
    C:\Java\home\src\forums>"C:\Program Files\Java\jdk1.6.0_12\bin\java.exe" -Xms512m -Xmx1536m -enableassertions -cp C:\Java\home\classes forums.NioBenchmark1
    copying SieveOfEratosthenesTest.txt 259678795 bytes
    forums.NioBenchmark1$IoCopier took 14.333866455 seconds
    forums.NioBenchmark1$NioCopier took 7.712665715 seconds
    forums.NioBenchmark1$NioCopier2 took 6.206867074 seconds
    Press any key to continue . . .Having said that... The NIO has lost a fair bit of it's charm... testing transferTo's return value and maintaining your own position in the file is "cumbsome" (IMHO)... I'm not even certain that mine is completely correct (?n+=pos or n+=pos+1?).... hmmm..
    Cheers. Keiths.

  • Distinguishing the lowest test score in a while loop

    Hi,
    I am working on a program that collects a series of test scores from the user. The program should tabulate the scores and it should highlight the lowest score amongst the other test scores, but there within lies the problem for me. This is what my program looks like at this moment:
    import java.util.*;
    public class ArrayOfTestScores
        public static void main(String[] args)
            int[] testScore = new int[5];
            int count, max, min, next, number;
            int sum, average, lowScore, bottomScore;
            Scanner keyboard  = new Scanner(System.in);
            lowestScore = 0;
            sum = 0;
            System.out.print("Enter score for test 1: ");
            max = keyboard.nextInt();
            number = 1;
            count = 1;
            while(count<5)
                System.out.print("Enter score for test" + (number+1) +": ");
                testScore[count] = keyboard.nextInt();
                testScore[0] = max;
                min = max;
                next = testScore[count];
                if(next > max)
                    max = next;
                else
                    min = next;
                    if(next < min)
                        min = next;
                    else
                        max = next;
                sum = sum + testScore[count];
                min=lowestScore;
                number++;
                count++;
            bottomScore = lowScore;
            for(count = 0; count < testScore.length; count++)
                if(testScore[count]==bottom)
                    System.out.println("Test" + (count+1)+ testScore[count]+ "lowest score");
                else
                    System.out.println("Test" + (count+1)+ testScore[count]);
    }Here is a sample of what the output looks like:
    Enter score for test 1: 50
    Enter score for test 2: 70
    Enter score for test 3: 22
    Enter score for test 4: 90
    Enter score for test 5: 99
    Test 1: 50
    Test 2: 70
    Test 3: 22 lowest score
    Test 4: 90
    Test 5: 99
    If there is anyone out there who can assist me with this program, I would appreciate it tremendously.

    Here's part of your codeelse
                    min = next;
                    if(next < min)
                        min = next;
                    else
                        max = next;
                }So, first min is set to the same value as next. Then you have an if statement that tests to see if next is less than min. How can that ever happen if min=next?

  • Windows 7 SP1 PRO SMB2 Client Behaviour Quirk - Last SMB2 Query_Info request in compounded requests, contains 1 extra byte in the end after file_id

    Hi,
    From the specification, SMB2 Query Info is defined as -Query_Info {
        uint16_t structure_size;
        uint8_t info_type;
        uint8_t file_info_class;
        uint32_t output_buf_len;
        uint16_t input_buffer_off;
        uint16_t res;
        uint32_t input_buf_len;
        uint32_t additional_information;
        uint32_t flags;
        uint8_t file_id[16];
    I am looking at smb traffic between 2 Windows 7 Pro machines and I see that for SMB Query_Info Request records, for some compounded requests, the last Query_Info request has an extra byte after the 16 byte file_id.  This is only for SMB2 Query_Info
    requests.
    On checking Query_Info requests that are single(not compounded), I don't see this extra byte.
    I have attached images below from wireshark for both with and without this extra byte, from the same flow.
    Can we consider this a quirk of the windows client issuing Query_Info Compounded requests?
    Image1 - http://postimg.org/image/th8fubvuz <- As you can see, this is a comounded series of requests and the last requset which is a query_info request *HAS* an extra byte after the file_id.
    Image2 - http://postimg.org/image/kkp4adxe7/ <- As you can, this is a compounded series of requests and the last request which is a query_info request, DOES *NOT* HAVE an extra byte after the file_id unlike Image1
    Image3- http://postimg.org/image/5w7061vrr/ <- As you can see, this is a single Query_Info request, and we don't have the extra byte here after the file_id.

    We worked with cressnet and resolved these questions offline. Here is a summary of resolution.
    Regarding the comments on compounded messages with QueryInfo,
    this is not specific to QueryInfo.
    The receiver’s transport layer delivers the message to the SMB2 layer (server/redirector). The SMB2 PDU starts with its header. The PDU is casted and interpreted based on the SMB2 command. What matters is the message’s structure
    itself.
    The transport’s (e.g. Nbtss or SMBoverTCP) indicates the length of its payload. Each SMB2 message has a structure which may include some variable length fields. Padding is one element that may complement the message for alignment
    purpose. Any extra byte (s) that is not part of the SMB2 message fields would be irrelevant and ignored.
    Regarding the comments on ErrorData,
    the CHANGE_NOTIFY response packets look valid as documented in the [MS-SMB2] specification. In this particular case, even if the error is not a success code (i.e. STATUS_NOTIFY_ENUM_DIR), the response is an empty CHANGE_NOTIFY
    Response, rather than a standard ERROR Response.
    The exception cases that are not considered error messages are listed in [MS-SMB2] section 3.3.4.4. When in doubt, please consult the server processing of the specific SMB2 command.
    [MS-SMB2] 3.3.4.4 Sending an Error Response
    https://msdn.microsoft.com/en-us/library/cc246722.aspx
    When the server is responding with a failure to any command sent by the client, the response message MUST be constructed as described here. An error code other than one of the following indicates a failure:
    •         STATUS_MORE_PROCESSING_REQUIRED in an SMB2 SESSION_SETUP Response specified in section 2.2.6.
    •         STATUS_BUFFER_OVERFLOW in an SMB2 QUERY_INFO Response specified in section 2.2.38.
    •         STATUS_BUFFER_OVERFLOW in a FSCTL_PIPE_TRANSCEIVE, FSCTL_PIPE_PEEK or FSCTL_DFS_GET_REFERRALS Response specified in section 2.2.32.<190>
    •         STATUS_BUFFER_OVERFLOW in an SMB2 READ Response on a named pipe specified in section 2.2.20.
    •         STATUS_INVALID_PARAMETER in an FSCTL_SRV_COPYCHUNK or FSCTL_SRV_COPYCHUNK_WRITE response, when returning an SRV_COPYCHUNK_RESPONSE as described in section 3.3.5.15.6.2.
    •         STATUS_NOTIFY_ENUM_DIR in an SMB2 CHANGE_NOTIFY Response specified in section 2.2.36.
    [MS-SMB2] 3.3.5.19 Receiving an SMB2 CHANGE_NOTIFY Request
    https://msdn.microsoft.com/en-us/library/cc246747.aspx
    Change notification processing in the object store MUST be handled as specified in section 3.3.1.3. It is also outlined in [MS-CIFS] section 3.3.5.59.4.
    If the server is unable to copy the results into the buffer of the SMB2 CHANGE_NOTIFY Response, then the server MUST construct the response as described below, with an OutputBufferLength of zero, and set the Status in the SMB2
    header to STATUS_NOTIFY_ENUM_DIR.
    Thanks,
    Edgar

  • Converting from unsigned int / short to byte[]

    Can anybody help me, I am trying to convert from:
    - unsigned int to byte[]
    - unsigned short to byte[]
    I will appreciate your help lots. thanks.

    @Op.
    This code converts an integer to a byte[], but you have to consider the byte order:
            int value = 0x12345678;
            byte[] result = new byte[4];
            for (int i=3; i>=0; i--) {
                result[i] = (byte)(value & 0xff);
                value = value >> 8;
            }This is another option:
            int dummy = 7;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(dummy);
            byte[] bytes = os.toByteArray();Kaj

  • 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!")
    }

  • Is there any way to retreive the FileName in the mapping

    Is there any way to retreive the FileName and so that I can use that in my mapping. This is FILE2RFC scenario with NO BPM.
       I am using the adapter specific message attributes in the file sender CC.
    Thanks,
    Ravi
    null

    Yes you can retreive it.  Create an simple user defined function in the mapping and use the following code.
    Imports: com.sap.aii.mapping.api.*;
    Parameter: String filename
    Paramter: String filename;
    filename = fileName + ".DAT";
    DynamicConfiguration conf = (DynamicConfiguration) container
    .getTransformationParameters()
    .get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "FileName");
    conf.put(key, filename);
    return filename;
    Or
    Just do whatever mentioned in this weblog:
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14
    ---Satish

  • How to update a large (over 4 million item) List(Of Byte) quickly by altering indexes contained in a Dictionary(Of Integer, Byte) where the Dictionaries keys are the indexes in the List(Of Byte) that need to be changed to the values for those indexes?

       I'm having some difficulty with transferring images from a UDP Client to a UDP Server. The issue is receiving the bytes necessary to update an original image sent from the Client to the Server and updating the Servers List(Of Byte) with the
    new bytes replacing bytes in that list. This is a simplex connection where the Sever receives and the Client sends to utilize the least amount of bandwidth for a "Remote Desktop" style application where the Server side needs image updates of whatever
    occurs on the Client desktop.
       So far I can tranfer images with no issue. The images can be be any image type (.Bmp, .Gif, .JPeg, .Png, etc). I was working with sending .JPeg's as they appear to be the smallest size image when a Bitmap is saved to a memory stream as type
    .JPeg. And then I am using GZip to compress that byte array again so it is much smaller. However on a loopback on my NIC the speed for sending a full size screen capture is not very fast as the Server updates fairly slowly unless the Clients screen capture
    Bitmap is reduced in size to about 1/3'd of the original size. Then about 12000 bytes or less are sent for each update.
       Due to .JPeg compression I suppose there is no way to get the difference in bytes between two .JPegs and only send those when something occurs on the desktop that alters the desktop screen capture image. Therefore I went to using .Bmp's as each
    .Bmp contains the same number of bytes in its array regardless of the image alterations on the desktop. So I suppose the difference in bytes from a second screen capture and an inital screen capture are what is different in the second image from the initial
    image.
       What I have done so far is save an initial Bitmap of a screen capture using a memory stream and saving as type .Bmp which takes less than 93 milliseconds for 4196406 bytes. Compressing that takes less than 118 milliseconds to 197325 bytes for
    the current windows on the desktop. When that is done PictureBox1 is updated from nothing to the captured image as the PictureBox's background image with image layout zoom and the PictureBox sized at 1/2 my screens width and 1/2 my screens height.
       Then I save a new Bitmap the same way which now contains different image information as the PictureBox is now displaying an image so its back color is no longer displayed (solid color Aqua) and the cursor has moved to a different location. The
    second Bitmap is also 4196406 in bytes and compressed it was 315473 bytes in size.
       I also just found code from this link Converting a Bitmap to a Byte Array (and Byte Array to Bitmap) which gets a byte array
    directly from a Bitmap and the size of that is 3148800 for whatever is full screen captured on my laptop. So I should be able to work with smaller byte arrays at some point.
       The issue I'm having is that once the Client sends an image of the desktop to the Server I only want to update the server with any differences occuring on the Clients desktop. So what I have done is compare the first screen captures bytes (stored
    in a List(Of Byte)) to the second screen captures bytes (stored in a List(Of Byte)) by using a For/Next for 0 to 4196405 where if a byte in the first screen captures List is not equal to a byte in the second screen captures List I add the index and byte of
    the second screen captures list to a Dictionary(Of Integer, Byte). The Dictionary then only contains the indexes and bytes that are different between the first screen capture and second screen capture. This takes about 125 milliseconds which I think is pretty
    fast for 4196406 byte comparison using a For/Next and adding all the different bytes and indexes for each byte to a Dictionary.
        The difference in Bytes between the inital screen capture and the second screen capture is 242587 as an example which changes of course. For that amount of bytes the Dictionary contains 242587 integers as indexes and 242587 bytes as different
    bytes totaling 485174 bytes for both arrays (keys, values).  Compressed the indexes go from 242587 to 43489 bytes and the values go from 242587 to 34982 bytes. Which means I will have to send 78, 481 bytes from the Client to the Server to update the display
    on the server. Quite smaller than the original 4196406 bytes of the second Bitmap saved to type .Bmp or the compressed size of that array which was 315473 bytes. Plus a few bytes I add as overhead so the server knows when an image array ends and how many packets
    were sent for the array so it can discard complete arrays if necessary since UDP is lossfull although probably not so much in current networks like it may originally have been when the internet started.
        In reality the data from the Client to the Server will mostly be the cursor as it moves and updating the Server image with only a few hundred bytes I would imagine at a time. Or when the cursor selects a Button for example and the Buttons
    color changes causing those differences in the original screen capture.
       But the problem is if I send the Dictionaries Indexes and Bytes to the Server then I need to update the original Bitmap List(Of Byte) on the server by removing the Bytes in the received informations Index locations array from the Servers Bitmap
    List(Of Byte) and replacing those Bytes with the Bytes in the received informations Byte array. This takes so long using a For/Next for however many indexes are in the received informations Index array to update the Bitmap List(Of Byte) on the server using
    "Bmp1Bytes.RemoveAt(Index As Integer)" followed by "Bmp1Bytes.Insert(Index As Integer, Item As Byte)" in the For/Next.
        I've tried various For/Next statements including using a new List(Of Byte) with If statements so If the the integer for the For/Next ='s the Key in a Dictionary(Of Integer, Byte) using a Counter to provide the Dictionaries Key value then
    the Dictionaries byte value will be added to the List(Of Byte) and the counter will increas by one Else the List(Of Byte) adds the original "Bmp1Bytes" byte at that index to the new List(Of Byte). This takes forever also.
       I also tried the same For/Next adding to a new Dictionary(Of Integer, Byte) but that takes forever too.
       I think I could use RemoveRange and AddRange to speed things up. But I don't know how to retrieve a contiguous range of indexes in the received indexes that need to be updated in the servers "Bmp1Bytes" List(Of Byte) from the received
    array of indexes and bytes which are in a Dictionary(Of Integer, Byte).  But I believe this would even be slower than some realistic method for replacing all Bytes in a List(Of Byte) when I have the indexes that need to be replaced and the bytes to replace
    them with.
       Even if I just used AddRange on a new List(Of Byte) to add ranges of bytes from the original "Bmp1Bytes" and the changes from the Dictionary(Of Integer, Byte) I think this would be rather slow. Although I don't know how to do that
    by getting contiguous ranges of indexes from the Dictionaries keys.
       So I was wondering if there is some method perhaps using Linq or IEnumerable which I've been unable to figure anything out which could do this.
       I do have some copy and pasted code which I don't understand how it works that I am using which I would guess could be altered for doing something like this but I can't find information that provides how the code works.  Or even if I did
    maybe I can't understand it. Like the code below which is extremely fast.
       Dim strArray() As String = Array.ConvertAll(Of Integer, String)(BmpComparisonDict.Keys.ToArray, Function(x) x.ToString())
    La vida loca

    Monkeyboy,
    That was quite a bit to read, but still a bit unclear. Could you put a specific list of goals/questions, asked in the smallest possible form?
    It seems like either you're making a program that monitors activity on your computer, or you're writing some kind of remote pc app.
    When you do get your bytes from using lockbits, keep in mind all the files header info would be lost. I think retaining the header info is worth the extra bytes.
    The other, thing: I'm not sure if you're taking 32bpp screen shots, but also keep in mind that the "whole desktop" is the final destination for blended graphics, if that makes sense. What I mean is that there is no need to capture an "alpha"
    channel for a desktop screenshot, as alpha would always be 255, this could save you 1 byte per pixel captured... Theres nothing "behind" the desktop, therefore no alpha, and every window shown above the desktop is already blended. I suggest using
    24Bpp for a full screen capture.
    Your X,Y information for the mouse could be stored as UINT16, this would save you a measly 2 bytes per location update/save.
    When you update your byte arrays, maybe you can turn the array into a stream and write to whatever index, however many bytes, that should prevent a "Shift" of bytes, and instead overwrite any bytes that "get in the way".
    ex
    Dim example As String = "This is an example."
    Dim insertString As String = "was"
    Dim insertBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(insertString)
    Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(example)
    Dim modifiedBytes As Byte() = {}
    Using ms As New System.IO.MemoryStream(bytes)
    ms.Position = 5
    ms.Write(insertBytes, 0, 3)
    modifiedBytes = ms.ToArray
    End Using
    Dim newString As String = System.Text.Encoding.ASCII.GetString(modifiedBytes)
    'Notice how below there isn't the word "is" anymore, and that there isn't a
    'space.
    'This demonstrates that you overwrite existing data, versus shifting everything to
    'the right.
    'Returns: This wasan example.
    MsgBox(newString)
    “If you want something you've never had, you need to do something you've never done.”
    Don't forget to mark
    helpful posts and answers
    ! Answer an interesting question? Write a
    new article
    about it! My Articles
    *This post does not reflect the opinion of Microsoft, or its employees.
    Well it's too much to read. I was really tired when I wrote it. Even the below is too much to read but perhaps gets the point across of what I would like to do which I think
    Joel Engineer may have answered but I'm not sure. As I'm still too tired to understand that yet and research what he said in order to figure it out yet.
    But maybe the code below can provide the concept of the operation with the comments in it. But seeing as how I'm still tired it may be confused.
    Option Strict On
    Imports System.Windows.Forms
    Imports System.IO
    Imports System.IO.Compression
    Imports System.Drawing.Imaging
    Imports System.Runtime.InteropServices
    Public Class Form1
    Dim Bmp1Bytes As New List(Of Byte)
    Dim Bmp1BytesCompressed As New List(Of Byte)
    Dim Bmp2Bytes As New List(Of Byte)
    Dim BmpComparisonDict As New Dictionary(Of Integer, Byte)
    Dim BmpDifferenceIndexesCompressed As New List(Of Byte)
    Dim BmpDifferenceBytesCompressed As New List(Of Byte)
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    SomeSub()
    End Sub
    Private Sub SomeSub()
    ' Pretend this code is in UDP Client app. A screen capture is performed of the desktop. Takes about 90 milliseconds.
    Bmp1Bytes.Clear()
    Using BMP1 As New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)
    Using g1 As Graphics = Graphics.FromImage(BMP1)
    g1.CopyFromScreen(0, 0, 0, 0, BMP1.Size)
    Cursor.Draw(g1, New Rectangle(Cursor.Position.X, Cursor.Position.Y, Cursor.Size.Width, Cursor.Size.Height))
    Using MS As New MemoryStream
    BMP1.Save(MS, System.Drawing.Imaging.ImageFormat.Bmp)
    Bmp1Bytes.AddRange(MS.ToArray)
    End Using
    End Using
    End Using
    Bmp1BytesCompressed.AddRange(Compress(Bmp1Bytes.ToArray))
    ' UDP Client app sends Bmp1BytesCompressed.ToArray to UDP Server which is the entire image of the desktop that the UDP
    ' Client is on. This image takes awhile to send since compressed it is about 177000 bytes from over 4000000 bytes.
    ' I will be using different code just to get the bytes from the actual Bitmap in the future. That is not important for now.
    ' Pretend the UDP Server has received the bytes, decompressed the array received into a List(Of Byte) and is displaying
    ' the image of the UDP Clients desktop in a PictureBox.
    ' Now the image on the UDP Clients desktop changes due to the mouse cursor moving as an example. Therefore a new Bitmap
    ' is created from a screen capture. This takes about 90 milliseconds.
    Bmp2Bytes.Clear()
    Using BMP2 As New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)
    Using g1 As Graphics = Graphics.FromImage(BMP2)
    g1.CopyFromScreen(0, 0, 0, 0, BMP2.Size)
    Cursor.Draw(g1, New Rectangle(Cursor.Position.X, Cursor.Position.Y, Cursor.Size.Width, Cursor.Size.Height))
    Using MS As New MemoryStream
    BMP2.Save(MS, System.Drawing.Imaging.ImageFormat.Bmp)
    Bmp2Bytes.AddRange(MS.ToArray)
    End Using
    End Using
    End Using
    ' Now I have the original images bytes in Bmp1Bytes and the new images bytes in Bmp2Bytes on the UDP Client. But I don't
    ' want to send all of the bytes in Bmp2Bytes to the UDP Server. Just the indexes of and the bytes that are different in
    ' Bmp2Bytes from Bmp1Bytes.
    ' This takes less than 100 milliseconds for what I've tested so far where over 500000 bytes in Bmp2Bytes are different
    ' than the bytes in Bmp1Bytes. Usually that amount would be much less. But during testing I was displaying the image
    ' from Bmp1 bytes in a PictureBox so a large amount of data would change between the first screen shot, the PictureBox
    ' then displaying an image on the same PC and then the second screen shot.
    BmpComparisonDict.Clear()
    For i = 0 To Bmp1Bytes.Count - 1
    If Bmp1Bytes(i) <> Bmp2Bytes(i) Then
    BmpComparisonDict.Add(i, Bmp2Bytes(i))
    End If
    Next
    ' So now I have all the difference bytes and their indexes from Bmp2Bytes in the BmpComparisonDict. So I compress
    ' the indexes into on List and the Bytes into another List.
    BmpDifferenceIndexesCompressed.Clear()
    BmpDifferenceBytesCompressed.Clear()
    BmpDifferenceIndexesCompressed.AddRange(Compress(BmpComparisonDict.Keys.SelectMany(Function(d) BitConverter.GetBytes(d)).ToArray()))
    BmpDifferenceBytesCompressed.AddRange(Compress(BmpComparisonDict.Values.ToArray))
    ' Now pretend the UDP Client has sent both those arrays to the UDP Server which has added both decompressed arrays
    ' to a Dictionary(Of Integer, Byte). And the server has the original image decompressed bytes received in a List
    ' called Bmp1Bytes also.
    ' This is where I am stuck. The UDP Server has the Dictionary. That part was fast. However there is no
    ' fast method I have found for creating a new List(Of Byte) where bytes in the originally received List(Of Byte) that
    ' do not have to be altered are placed into a new List(Of Byte) except for the indexes listed in the
    ' Dictionary(Of Integer, Byte) that need to be placed into the appropriate index locations of the new List(Of Byte).
    ' The below example for doing so is exceptionally slow. Pretend UpdateDictionary has all of the decompressed indexes
    ' and bytes received by the UDP Server for the update contained within it.
    Dim UpdateDictionary As New Dictionary(Of Integer, Byte)
    Dim UpdatedBytes As New List(Of Byte)
    Dim Counter As Integer = 0
    For i = 0 To Bmp1Bytes.Count - 1
    If i = UpdateDictionary.Keys(Counter) Then ' Provides the index contained in the Keys for the Dictionary
    UpdatedBytes.Add(UpdateDictionary.Values(Counter))
    Counter += 1
    If Counter > UpdateDictionary.Count - 1 Then Counter = 0
    Else
    UpdatedBytes.Add(Bmp1Bytes(i))
    End If
    Next
    ' So what I'm trying to do is find an extremely fast method for performing something similar to what the
    ' above operation performs.
    End Sub
    Private Function Compress(BytesToCompress() As Byte) As List(Of Byte)
    Dim BytesCompressed As New List(Of Byte)
    Using compressedStream = New MemoryStream()
    Using zipStream = New GZipStream(compressedStream, CompressionMode.Compress)
    zipStream.Write(BytesToCompress, 0, BytesToCompress.Count)
    zipStream.Close()
    BytesCompressed.AddRange(compressedStream.ToArray)
    End Using
    End Using
    Return BytesCompressed
    End Function
    Private Function Decompress(BytesToDecompress() As Byte) As List(Of Byte)
    Dim BytesDecompressed As New List(Of Byte)
    Using DecompressedStream = New MemoryStream()
    Using zipStream = New GZipStream(DecompressedStream, CompressionMode.Decompress)
    zipStream.Write(BytesToDecompress, 0, BytesToDecompress.Count)
    zipStream.Close()
    BytesDecompressed.AddRange(DecompressedStream.ToArray)
    End Using
    End Using
    Return BytesDecompressed
    End Function
    End Class
    La vida loca

  • When i am retreiving the values from the access table i am getting null val

    hi all,
    I comeacross the following problem,I connected my applet to the Access database with jdbc:odbc driver.
    I am trying to retreive the values from the table.I am getting the result correctly when the same code with using applet it was giving the correct result.
    when I am using an applet program it was giving the null value istead of the actual records.
    can anybody tell me the reason why
    thanks in advance
    and also how to connect the databse in the webserver when i installed my applet in the client side
    please give me some suggestions to do that
    thankyou
    lakshman

    Hi Krishna,
    Can you please copy the code generated by ODI for creating your C$ table ?
    i mean :- create table C$_0Entity ( from the operator log
    Regards,
    Rathish A M

  • Hi...My IPod touch was recently stolen. I have an Itunes account..can I retreive the serial number of my IPod Touch from my Itunes account? If, so...how may I do this. If I have the serial number, the local police can check the serial numbers at pawn shop

    Hi...My Ipod Touch was recently stolen. In order to help the local police deptartment I need to supply a seria number for the Ipod. Of course, I did not wrtie down the serial number, but I have used he device on my Itunes account. My question: Is there a way to retreive the serial nuber of my Ipod touch from my Itunes account? Thanks you all....

    Yes. See bold below
    - If you previously turned on FIndMyiPod on the iPod in Settings>iCloud and wifi is on and connected go to iCloud: Find My iPhone, sign in and go to FIndMyiPhone. If the iPod has been restored it will never show up.
    - You can also wipe/erase the iPod and have the iPod play a sound via iCloud.
    - If not shown, then you will have to use the old fashioned way, like if you lost a wallet or purse.
    - Change the passwords for all accounts used on the iPod and report to police
    - There is no way to prevent someone from restoring the iPod (it erases it) using it unless you had iOS 7 on the device. With iOS 7, one has to enter the Apple ID and password to restore the device.
    - Apple will do nothing without a court order                                                        
    Reporting a lost or stolen Apple product                                               
    - iOS: How to find the serial number, IMEI, MEID, CDN, and ICCID number

  • My ipad2 was recently stolen.  I have since purchased an iphone4.  Is there a way to retreive the apps that were on the ipad for use on my iphone or a new ipad once purchased?

    My ipad2 was recently stolen.  I have since purchased an iphone4.  Is there a way to retreive the apps that I had on my ipad for use on my iphone or on a new ipad if purchased?
    Thx.
    Adam

    Downloading past purchases from the App Store, iBookstore, and iTunes Store
    All ipad apps are not neccessarily compatible with iphone.  There are some universal apps.

  • My Icloud is tuck on my old email adress. i can not retreive the password becaue when i request the email it doent get sent to thi adress. how can i change it sothat my icloud is on my new email. i cant login or out of icloud now.

    My Icloud is tuck on my old email adress. i can not retreive the password becaue when i request the email it doent get sent to thi adress. how can i change it sothat my icloud is on my new email. i cant login or out of icloud now.

    To change the iCloud ID on your phone you have to go to Settings>iCloud, tap Delete Account, provide the password for the old ID when prompted to turn off Find My iPhone, then sign back in with the ID you wish to use.  If you don't know the password for your old ID, or if it isn't accepted, go to https://appleid.apple.com, click Manage my Apple ID and sign in with your current iCloud ID.  Tap edit next to the primary email account, change it back to your old email address and save the change.  Then edit the name of the account to change it back to your old email address.  You can now use your current password to turn off Find My iPhone on your device, even though it prompts you for the password for your old account ID. Then go to Settings>iCloud, tap Delete Account and choose Delete from My iDevice when prompted (your iCloud data will still be in iCloud).  Next, go back to https://appleid.apple.com and change your primary email address and iCloud ID name back to the way it was.  Now you can go to Settings>iCloud and sign in with your current iCloud ID and password.

  • Components in the lowest level of costing structure in SO

    Hi,
    Could you please let me know is any function module to get  Components in the lowest level of costing structure in Sales order.
    Thanks,
    Harinath

    Yes, you can manipulate your components any way you like. Becareful about the layout manager though as it likes to handle the positioning and sizing, so there is an intimate relationship there.
    Also call validate() on the container after you make your changes.

Maybe you are looking for