Bitwise & with 0xFF

Folks, Looking at a piece of code, didn't understand why do we need to do a bitwise & with 0xFF.
StringBuffer sb = new StringBuffer("F1");
short hexNum = Short.parseShort(sb.toString(), 16);
b[bufIdx] = (byte) (*hexNum & 0xFF*);
As we are casting it to byte, the upper byte would be truncated anyways? If I don't get it right, can someone please explain the logic?
TIA!

From the JLS:
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. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
--[http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363]
So yeah, I personally can't see any case in which this:
byte b = (byte)(someInt);would be any different than this:
byte b = (byte)(someInt & 0xFF);Since the JLS explicitly states that all but the last 8 bits will be discarded, and ( & 0xFF ) is guaranteed not to change anything in the last 8 bits.
If you had an example in which the two results would be different, I might be able to explain why...

Similar Messages

  • Help with a Subnet mask solution?

    This is probably obvious to many of your network guys/gals - but I'm stumped - I'm looking for an easy solution to this.
    I have a Linksys wireless router WRT54GS - Comcast cable broadband - my MacBook wasn't staying connected to it so I plugged in my Airport Express to one of the Linksys ports via Ethernet and disabled the wireless on the Linksys.
    Bingo - no more connection problem - the Linksys handles the wired users and the Airport Express handles the wireless - except - I have a network drive connected to the Linksys via Ethernet that my wireless users can't "see" - I believe - because it's on a different subnet mask.
    Is there an easy way to "link" the two so my wireless users can see the wired network drive?
    THANKS!

    As both the Linksys and the AE act as normal switches with no routing functionality, you have one single subnet. So all you have to do is to make sure that all devices connected to the Linksys and the AE have an IP-address of that subnet and the same subnet mask.
    Most routers have a class C private network configured by default. Let's assume, you have 192.168.0.0/255.255.255.0. If so, pick an IP-address out of the address range 192.168.0.1 to 192.168.0.254 for each device and use 255.255.255.0 as a subnet mask. For other class C private networks use the according range.
    If you need to mix different class C networks (e.g. 192.168.0.x for your wired deviced and 192.168.1.x for your wireless devices) use a subnet mask of 255.255.0.0 on all devices.
    Just for your understanding: when a machine A connects to a machine B, machine A takes it's own IP-address (e.g. 192.168.1.1) and ANDs it bitwise with it's subnet address (e.g. 255.255.255.0 would result in 192.168.1.0). Next it does the same again, with machines B IP address and it's own subnet mask. If both results are the same, both machines are on the same subnet, so machine A tries to connect machine B directly. If not, the machines are on different subnet, so machine A tries to connect to machine B using it's configured default gateway.
    Hope this information helps at least a bit.

  • Problem with WMS themes & Oracle MapViewer Version 11.1.1.2

    Hello, in my application I load the background raster from a external server using wms. With differents version of mapviewer 11 with a weblogic server (e.g: release 1, release 11.1.1.4) all it's allrigth, but when I change the mapviewer to release 11.1.1.2 I can't see the raster and I get the next error:
    21-sep-2011 11:33:10 oracle.sdovis.theme.WMSMapThemeDefinition setSrs
    INFO: Theme SRID set to 23030 for EPSG 82337
    21-sep-2011 11:33:10 oracle.sdovis.theme.WMSMapThemeProducer prepareData
    SEVERE: MAPVIEWER-01048: Cannot load WMS map image.
    21-sep-2011 11:33:10 oracle.sdovis.theme.DynGeomThemeProducer prepareData
    I can understand why..., I don't know what's is the problem because differents versions of mapviewer work without problem on the same weblogic server (Weblogic 11 patchset R2).
    Anyone know if mapviewer 11.1.1.2 has a problem with WMS?
    Thanks for your answer!!

    although with Oracle Fusion Middleware MapViewer Version 11g ps3 (11.1.1.4) and 11g ps4 (11.1.1.5.1) everything work ok in my WebLogic Server: 10.3.3.0, with Mapviewer Version 11.1.1.2 I get the next error:
    29-sep-2011 13:25:53 oracle.sdovis.theme.WMSMapThemeDefinition setSrs
    INFO: Theme SRID set to 23030 for EPSG 82337
    sun.awt.image.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
         at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
         at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:119)
         at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
         at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
         at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    29-sep-2011 13:25:53 oracle.sdovis.theme.WMSMapThemeProducer prepareData
    SEVERE: MAPVIEWER-01048: Cannot load WMS map image.
    I've seen that the wms external service works ok and returns an url with the correct image, but something wrong happens inside of mapviewer that don't allow generate the image....

  • Cisco Terminal Server cannot forward "0xFF"

    Hi..
    I have topology setup as attached, where server is established reverse telnet session to router 2911 with asyncronous line connected to terminal host.
    basically all setup is done and everything work fine, where terminal host (PC) can talk with server over serial line.
    here come the issue, after sometime, the communication between server and terminal host stall. and after  a while the communication resume. after some troubleshooting and verification, the server team use protocol analyzer to see incoming serial packet and he mentioned that there are some payload within TCP is missing whic is "0xFF" hexadecimal, thus make terminal host can not ack the packet because it think the packet is corrupted (not complete).
    i tried to figured out and do capture traffic using wireshark at switch (port connected to router) but it seem the server team correct.
    at first everything work fine, but whenever server send packet with 0xFF inside the payload, the terminal host can not "ack" the packet.
    anyone encounter this issue before? thanks in advance for helping out.
    regards,
    RANO
    =============================
    the configuration as below:
    aaa authentication login NONE none
    interface Async0/0/0
    no ip address
    encapsulation ppp
    <ommited>
    line 0/0/0 0/1/15
    session-timeout 10
    exec-timeout 0 0
    login authentication NONE
    no exec
    no editing
    transport input all
    stopbits 1
    output of show line :
       Tty Line Typ     Tx/Rx    A Modem  Roty AccO AccI  Uses  Noise Overruns  Int
    *     0    0 CTY              -    -      -    -    -     0      0    0/0      -
          1    1 AUX   9600/9600  -    -      -    -    -     0      0    0/0      -
    *  0/0/0    3 TTY   9600/9600  -    -      -    -    -     2      0    0/0      -
      0/0/1    4 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/2    5 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/3    6 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/4    7 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/5    8 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/6    9 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/7   10 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/8   11 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/0/9   12 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/10   13 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/11   14 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/12   15 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/13   16 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/14   17 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/0/15   18 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/0   19 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/1   20 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/2   21 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/3   22 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
       Tty Line Typ     Tx/Rx    A Modem  Roty AccO AccI  Uses  Noise Overruns  Int
      0/1/4   23 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/5   24 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/6   25 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/7   26 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/8   27 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
      0/1/9   28 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/10   29 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/11   30 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/12   31 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/13   32 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/14   33 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
    0/1/15   34 TTY   9600/9600  -    -      -    -    -     0      0    0/0      -
        388  388 VTY              -    -      -    -    -     0      0    0/0      -
        389  389 VTY              -    -      -    -    -     0      0    0/0      -
        390  390 VTY              -    -      -    -    -     0      0    0/0      -
        391  391 VTY              -    -      -    -    -     0      0    0/0      -
        392  392 VTY              -    -      -    -    -     0      0    0/0      -
        393  393 VTY              -    -      -    -    -     0      0    0/0      -
        394  394 VTY              -    -      -    -    -     0      0    0/0      -
        395  395 VTY              -    -      -    -    -     0      0    0/0      -
        396  396 VTY              -    -      -    -    -     0      0    0/0      -
        397  397 VTY              -    -      -    -    -     0      0    0/0      -
       Tty Line Typ     Tx/Rx    A Modem  Roty AccO AccI  Uses  Noise Overruns  Int
        398  398 VTY              -    -      -    -    -     0      0    0/0      -
        399  399 VTY              -    -      -    -    -     0      0    0/0      -
        400  400 VTY              -    -      -    -    -     0      0    0/0      -
        401  401 VTY              -    -      -    -    -     0      0    0/0      -
        402  402 VTY              -    -      -    -    -     0      0    0/0      -
        403  403 VTY              -    -      -    -    -     0      0    0/0      -
    Line(s) not in async mode -or- with no hardware support:
    2, 35-387

    We are using port 2035.
    Here is the exsiting line config and show line status:
    =======================
    line 35
    location SRGEM1
    no activation-character
    special-character-bits 8
    transport preferred telnet
    transport input pad telnet rlogin
    transport output pad telnet rlogin
    telnet refuse-negotiations
    stopbits 1
    tserv001#show line 35
    Tty Typ Tx/Rx A Modem Roty AccO AccI Uses Noise Overruns Int
    35 TTY 9600/9600 - - - - - 58 1 0/0 -
    Ready
    Line 35, Location: "SRGEM1", Type: ""
    Length: 24 lines, Width: 80 columns
    Baud rate (TX/RX) is 9600/9600, no parity, 1 stopbits, 8 databits
    Status: Ready
    Capabilities: Refuse Telnet Echo, Refuse Suppress-GA
    Modem state: Ready
    Modem hardware state: noCTS* noDSR* DTR RTS
    Special Chars: Escape Hold Stop Start Disconnect Activation
    ^^x none - - none any
    Timeouts: Idle EXEC Idle Session Modem Answer Session Dispatch
    00:10:00 never none not set
    Idle Session Disconnect Warning
    never
    Login-sequence User Response
    00:00:30
    Autoselect Initial Wait
    not set
    Modem type is unknown.
    Session limit is not set.
    Time since activation: never
    Editing is enabled.
    History is enabled, history size is 20.
    DNS resolution in show commands is enabled
    Full user help is disabled
    Allowed input transports are pad telnet rlogin.
    Allowed output transports are pad telnet rlogin.
    Preferred transport is telnet.
    No output characters are padded
    No special data dispatching characters
    =====================
    What are the behavioral differences between 2xxx, 4xxx and 6xxx ports?
    Thanks for your help.

  • UdpClient with multiple threads using ReceiveAsync get the same buffer

    Hello,
    First let me give you the premise that I am working under... I am hoping to have multiple receive threads to make sure that I am pulling data off the port as quickly as possible and am hoping to do this efficiently through using asynchronous functions.
    I have two simple applications which I will include the code of below, one that uses 4 ReceiveAsync threads and another that sends data out, very quickly. I am finding that the data that I receive is not the same as what I sent. For instance I receive the
    same packet twice and others not at all. I get the output from my receive client:
    Receive client running...
    Packet 1 - 02-FF-FF-FF-FF-FF
    Packet 2 - 03-FF-FF-FF-FF-FF
    Packet 3 - 01-FF-FF-FF-FF-FF
    Packet 4 - 01-FF-FF-FF-FF-FF
    Notice that packet starting with 00 is missing and instead i have two 01s... Sometimes when I run all 4 packets start with 03. I have verified that all 4 packets are correct on the receive machine using Wireshark.
    Can anyone help me figure out why I am getting the right number of continuations from ReceiveAsync with the wrong packets?
    The Sender:
    class Program
        static int numberOfPktsToSend = 4;
        static void Main(string[] args)
            var localEP = new IPEndPoint(IPAddress.Parse("192.168.209.1"), 47000);
            var remoteEP = new IPEndPoint(IPAddress.Parse("192.168.209.133"), 47000);
            UdpClient client = new UdpClient(localEP);
            Parallel.For(0, numberOfPktsToSend, (x) =>
                client.SendAsync(new byte[] { (byte)x, 0xff, 0xff, 0xff, 0xff, 0xff }, 6, remoteEP);
                Console.WriteLine(string.Format("Sent {0}", x));
            Console.ReadLine();
    Note: I padded it with 0xff just to make the packets a little bigger.
    Receiver:
    class Program
        public static UdpClient client;
        public static CancellationTokenSource cts;
        private static int NumberOfReceiveThreads = 4;
        static int packetCount = 1;
        static void Main(string[] args)
            cts = new CancellationTokenSource();
            var localEP = new IPEndPoint(IPAddress.Parse("192.168.209.133"), 47000);
            client = new UdpClient(localEP);
            for (int i = 0; i < NumberOfReceiveThreads; i++)
                Task.Run(() => { myReceiveAsyncThread(); });
            Console.WriteLine("Receive client running...");
            Console.ReadLine();
            cts.Cancel();
        static async void myReceiveAsyncThread()
            var threadId = Task.CurrentId.ToString();
            while (!cts.IsCancellationRequested)
                try
                    var data = await client.ReceiveAsync();
                    Console.WriteLine(string.Format("Packet {0} - {1}", packetCount++, BitConverter.ToString(data.Buffer)));
                catch (Exception e)
                    Console.WriteLine("Something bad happened...");
    Thank you for your help!

    Hello Robbie,
    >>Can anyone help me figure out why I am getting the right number of continuations from ReceiveAsync with the wrong packets?
    Please have a try to use only one thread to read these byte stream as:
    cts = new CancellationTokenSource();
    var localEP = new IPEndPoint(IPAddress.Parse("10.168.196.246"), 47000);
    client = new UdpClient(localEP);
    //for (int i = 0; i < 1; i++)
    Task.Run(() => { myReceiveAsyncThread(); });
    Console.WriteLine("Receive client running...");
    Console.ReadLine();
    cts.Cancel();
    In your original code, there are multi threads seems to result a repeat read behavior.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Converting bytes to unsigned bytes

          int u=0;
          int i=32;
    byte []  data1 = new byte[1024];
    int[] unsignedValue=new int[1024];
    while(u<100){
                        unsignedValue[u] =data1[i] & 0xff;
                          u++;
                          i++;
                       } from input stream iam storing bytes in data1.now i want to convert specific bytes to unsigned bytes.
    here i tryed in the above way but i want to convert
    2 to 8
    12 to 18
    22 to 28
    bytes to unsigned and i want to store how can i do this?

    nanda_java wrote:
    in my fist post only i multiplyes with 0xff .and i gave code ...my question is how to multiply only specific
    2 to 8
    12 to 18
    22 to 28
    bytes with 0xff .the bytes are in data1.I have no idea what you're saying, and I have no idea what the significance of those ranges is.
    Look, you've already been told this twice: Say you get the byte 0xFE. That byte is neither signed nor unsigned. Get that into your head. It's simply a byte. The concept of signed/unsigned only comes into play when you decide to treat that as an integer value. You might want it to represent -2, or you might want it to represent 254. If you store it in a Java byte, it will represent -2. You cannot change that. If you want 0xFE to mean 254, then mask it with 0xFF and store it in an int.
    byte b = -2;
    System.out.println(b & 0xFF); // prints 254Furthermore, as already stated, in many cases it doesn't matter if it's signed or unsigned. If you do addtion, subtraction, multiplication (I think), AND, OR, XOR, you'll get the same byte result, regardless of whether you consider it signed or unsigned, and again, signed/unsigned only matters if you care about the numerical value of that signed result, rather than simply its bit pattern. 0xFE - 0x01 = 0xFD, and you can take that as -2 -1 = -3 or as 254 - 1 = 253. The bytes are the same regardless.
    What part are you not understanding? Don't just keep repeating the same thing about how it's unsigned and 2 to 8 and all that nonsense.
    So please, define your problem more clearly.
    Edited by: jverd on Jan 10, 2008 8:53 AM

  • Customising character sets

    We are trying to migrate to an oracle 8.1.7 database with UTF8 as database character set. A lot of the clients (windows) will still be using a company-specific character set, so there was an need to define/compile/install this character set in the NLS directory of oracle using .nlt files and the lxinst utility.
    While was trying to do this, a some questions emerged that where not addressed in the oracle documentation for NLS and Globalisation.
    The custom character set is based on the US-ASCII character set, so I thought to use
    base_char_set = US7ASCII
    and define the other characters starting from 0x80 and ending with 0xff
    -     but when I tried to compile this charset on AIX (server side) it gave a lot of warnings:
    LXI-WARN-00510: In lx22712.nlt at line 88, unicode 0x300 out of private use range
    LXI-WARN-00512: In lx22712.nlt at line 88, character 0x80 is remapped
    LXI-WARN-00510: In lx22712.nlt at line 89, unicode 0x302 out of private use range
    LXI-WARN-00512: In lx22712.nlt at line 89, character 0x81 is remapped
    -     when I tried to compile this on windows 2000 (client side) lxinst generates an application error
    Because this base_char_set definition did not work (or I made a mistake), I left it out of the definition file, and I mapped the characters using:
    character_data = {
    0x00 - 0x7f : 0x0000 - 0x007f,
    this compiles fine on both platforms. But this means that I have to fill in the classification list, the upper-to-lower and lower-to-upper relationships for all these characters, so it would be a lot easier if this base_char_set worked.
    other questions:
    -     About the character classification list:
    can such a list contain more than 2 classifications? For example
    0xC0 = {LETTER, UPPER, PRINTABLE}
    what are exactly the differences between those classifications? (for example can a character be a LETTER but not PRINTABLE)
    -     What about combining characters: in most character sets (also in ours) a combining character precedes the character it will be combined with, in a string. In Unicode the combining character comes after the character it will be combined with. When oracle converts strings between two such charsets, will the combining characters be handled according to the character set it is converting to, or will the order of characters in the string stay the same?
    --Janick                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Thanks for the help,
    the reason for needing a customised character set is not because of a special input device. Our current client uses this character set (not a standard) to support scripts for different languages. Since we want future clients to use the unicode standard, and want to support more scripts in the future, we are migrating our DB to UTF8, but our old clients should still be able to connect and query the DB (for now).
    I cannot find this developers version of the OLB. In
    Oracle Technology Network > Software >
    there is no entry in the drop down boxes for this (or am I looking in the wrong place?)
    thank you a lot for the help,
    regards,
    --Janick                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

  • How to cram two bytes into a short?

    Hi all,
    I have some byte[] data that I am receiving, and I need to put two bytes into one short (or int, or whatever), as the byte[] will form a two bytes-per-pixel image. I've been working with 8-bit data (this is 12-bits, NOT packed), which is much easier to manipulate.
    I currently have this method to convert a byte[] of 8-bit data into a short (I do this because Java does not support signed types and I need that 8th bit):
    private short[] convertBytesToShorts(byte[] data) {
         short[] convertedData = new short[data.length];
         for (int i = 0; i < data.length; i++) {
              convertedData[i] = (short)((short)data[i] & 0xff);
         return convertedData;
    }Is there a way to modify this to place two bytes into one short? Is it possible to just AND two bytes with 0xff and add them together to create one short? Surely it cannot be that simple. Also, remember that I must treat the values as unsigned.
    Furthermore, the two bytes look like this:
    | xxxx xxxx | xxxx 0000 |So the last four bits in the second byte are 0s.
    Any advice is appreciated.
    Message was edited by:
    Djaunl

    I've been working with 8-bit
    data (this is 12-bits, NOT packed), Obviously that is contradictory.
    I currently have this method to convert a byte[] of
    8-bit data into a short (I do this because Java does
    not support signed types and I need that 8th bit):
    Yes it does. The fact that it displays a byte as and integer and the conversion in that process produces a negative display value has nothing at all to do with the bits.
    Is there a way to modify this to place two bytes into
    one short? short s = (short)(((b1 << 8) & 0x0ff) | (b2 & 0x0ff))
    Of course you still have to deal with getting the order correct.
    (You can probably get rid of that first mask but you would need to test that.)

  • Decoding Run Length Encoded String

    I have a class that reads data from a server using a BufferedReader. The data is read into a char[]. This data has been Run Length Encoded by a seperate process.
    I loop through the char[] looking for a sentinal value. Once this value is found, I look at the next char to find the length and then the next char to find the value that needs to be populated.
    In order to correctly determine the length, I & the char with 0xff. This works most of the time. What I am seeing is that in certain circumstances the value is not what I expect. For example, in the following hex representation:
    F0 8B 20
    FO is my sentinel. 8B tells me to pad for 139. And, 20 tells me the value is a Space. So my class should at this point add 139 spaces.
    However, even though I & the char with 0xff it interprets the decimal value as 57.
    Here is the Method that does the UnRLE:
    public static CharArrayWriter UnRle(char[] InBuffer)
            try {
                CharArrayWriter caWriter = new CharArrayWriter();
                if (IsRle(InBuffer)) {
                    int iLoop = 0, iByteRepeat = 0;
                    for (int iIdx = RLE_HEADER.length() + RLE_SENTINEL_LEN; iIdx < InBuffer.length; iIdx++) {     // Start after header
                        if (InBuffer[iIdx] == RLE_SENTINEL) {
                            if (InBuffer[iIdx + 1] == RLE_SENTINEL)                           
                                caWriter.write(RLE_SENTINEL);
                            else {                       
                                for (iLoop = 0; iLoop < (int)InBuffer[iIdx + 1] & 0xff; iLoop++)
                                    caWriter.write(InBuffer[iIdx + 2]);
                                iIdx += 2;
                        else
                            caWriter.write(InBuffer[iIdx]);
                else
                    caWriter.write(InBuffer);
                return caWriter;
            catch (Exception e) {
                System.err.println("UnRle Exception " + e.toString());
                return null;
        }Any ideas?
    Thanks,
    ABumgardner

    Readers and Writers expect to deal with 16-bit characters. You need to be using InputStream and OutputStream.

  • Java signed and VB6 unsigned

    Hello everyone
    I know I made 2 posts in the past few days about this problem, but at that time, I wasn't sure this IS the problem or some other issues I might not know about. So the posts were very confusing. I thought I might make this new one to simplify things.
    A quick overview, I need to convert a VB6 client to Java. The server is in VB6 and I can't modify its code. So no access. I do have the source code and the working version of the VB6 client however.
    The problem I have is how to pass byte value more then 127 to the VB server. Java use signed byte (-127 to 127) while VB uses unsigned. Using packet sniffing program (Ethereal), I know the VB6 client is passing bytes values 0x85, 0x9E to the server, while my Java client (in doing exact same thing) can only pass value 0x3F 0x3F instead. Anything below 127 (i.e alphabetical letters) is the same between the 2 of program.
    So my question is how one can pass signed Java bytes into VB6 unsigned bytes. I did some search on google and found this
    http://www.javaworld.com/javaforums/showflat.php?Cat=&Board=javabeginner&Number=9208&page=15&view=collapsed&sb=7&o=&fpart=1
    but still didn't help me. I still only can pass bytes below 127.
    Any help is appreciate. Thank you in advance!

    To understand how things work you have to distinguish between the "bits in the byte", which can vary between 0x00 and 0xff in Java as well as in VB, and the interpretation of these bits, which is different.
    While 0xff might be interpreted as 255 in VB, it is a -1 in Java.
    So if you want to send the byte value 0x85, just write e.g.
    byte by = (byte)0x85;and the byte will contain the correct bits. You can also use casting from an int or short and it will give correct results:
    int i = 255;
    byte by = (byte)i;will leave by with 0xff.
    In the other direction, you might consider converting your bytes to short or int. In this case you have to handle the negative values explicitly, e.g.
    byte by = (byte)0x85;   // you might have received this value from VB
    int i = by & 0xff;leaves the variable i with the value of 133.

  • Help ,ImageIO exception to read and write

    Hi,
    I'm dynamically creating image files through screens utility of java(prog name:- Test_ScreenShot.java) and saving
    them in memory sequentially(pic0.jpg,pic1.jpg....etc).Simultaneously I'm accessing the saved files from another
    independent application(Prog name:- Test_Main.java) through piping(executing the application like this "Java
    Test_Screens|Java Test_Main").The application is in infinite loop.I'm using Version JDK 1.5
    I use java Image to read and write image:-
    My application was running well for days.But now I'm getting sudden exceptions.
    I got an exception while trying to save an dynamically generated image file in the local memory using the Image
    class.In brief I'm getting exactly 3 types of exceptions:-
    1)java.io.FileNotFoundException: pic5.jpg (Access is denied)
    2)"Exception in thread "main" java.lang.NullPointerException
    3)Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
    Here is the code snippent I wrote:
    /* Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect);
    // save captured image to jpg file
    ImageIO.write(image, "jpg", new File(outFileName));*/
    And here is the exception I am finding (I never found this before, I executed the code many times )
    =====================================================================================================================
    1)Exception Type 1:-
    java.io.FileNotFoundException: pic5.jpg (Access is denied)
    at java.io.RandomAccessFile.open(Native Method)
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
    at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:44)
    at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:37)
    at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:391)
    at javax.imageio.ImageIO.write(ImageIO.java:1483)
    at Test_ScreenShot.main(Test_ScreenShot.java:112)
    at Test_Main.main(Test_Main.java:466)
    at Test_ScreenShot.main(Test_ScreenShot.java:129)
    2)Exception Type 2:-
    "Exception in thread "main" java.lang.NullPointerException
    at Picture.width(Picture.java:84)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:38)
    at Test_Main.main(Test_Main.java:88)"
    ============================================================================================
    Now I tried the following as alternative of ImageIO(from jdk 1.2)
    to read image:-
    FileInputStream fis = new FileInputStream(file);
    JPEGImageDecoder jpeg = JPEGCodec.createJPEGDecoder(fis);
    jpeg.decodeAsBufferedImage();
    fis.close();
    But after running a long time suddenly its giving following exceptions:-
    ==============================================================================================
    Exception Type 3:- )
    Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
    at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)
    at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source)
    Exception Type 4:- )
    javax.imageio.IIOException: Not a JPEG file: starts with 0xff 0xd9
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source)
    at javax.imageio.ImageIO.read(Unknown Source)
    at javax.imageio.ImageIO.read(Unknown Source)
    at Picture.<init>(Picture.java:22)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
    at Test_Main.main(Test_Main.java:88)
    Exception in thread "main" java.lang.RuntimeException: Could not open file: pic45.jpg
    at Picture.<init>(Picture.java:27)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
    at Test_Main.main(Test_Main.java:88)
    My question is:-
    1)Where is the actual problem?Is it any kind of bug?
    2)I'm using the concept of piping recently to execute the application.Can it be the cause?
         When I googled I found the following informations.There is a bug in ImageIO while trying to write image file.But
    I'm not sure about that it will be relevent here :-
    1)from sun's bug database:-
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6247985
    2)from SUN Developer Forums
    http://forum.java.sun.com/thread.jspa?threadID=768917&messageID=4382833
    3)from Java.NET forum(here they r getting the bug while they r using createScreenCapture() method of robot class,I am
    also using that in my code)
    http://forums.java.net/jive/thread.jspa?messageID=123247
    4)from SUN's archieve
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0207&L=java-imageio-interest&D=0&P=1483
    5)Here is the actual implemetation of ImageIO class.I'm getting error at 391 no. line.
    http://kickjava.com/src/javax/imageio/ImageIO.java.htm
    Thanks And Regards
    Subhadip

    Hello,
    I am writng to ask a doubt I have been encountered. I have an array of Image URL's and I am downloading the images using thses URL for each index. The example for an image URL will be as follows:
    http://www.firstmonday.org/issues/issue6_10/wiggins/google-3oct2001.gifIf the URL is abroken link, I am getting the exception. But if the URL is somewhat hanging (which means when u open that URL in IE or Mozilla, the statuc bar for downloading the image will be hanging).
    So i want to set a timer for every link while downloading. may be 10min. My idea is if in that 10min, if code does not completes downloading the images, then ignore that link and proceed furthur.
    Can u please tell me how to write this.. Please tell me any other idea to tackle this problem.
    Thank you,
    Chaitanya

  • Kollmorgen AKD CANopen communication in LabVIEW

    Hello,
    I'm trying to communicate with a Kollmorgen AKD drive via CANopen within LabVIEW 2012 and am having difficulty figuring out the formatting.  I have the CAN transceive example running and when I turn on the drive and let it boot up, I receive one CAN message, so I'm fairly confident my wiring, baud rate, and basic drive setup are correct.
    The LabVIEW example has fields for Arbitration ID and 8 data bytes but I can't figure out the formatting to get the drive to respond to any messages I try to send.  The Kollmorgen CAN manual is here:
    http://www.kollmorgen.com/zu-za/products/drives/servo/akd/_manuals/kollmorgen-akd-canopen-communicat...
    When the Kollmorgen drive has finished booting up, it sends out a message ID 0x701 (which is a little odd considering I set the address to 1) with data 0x00.  If I set my Arbitration ID to 0x701 and set the RTR Flag in my LabVIEW example, then when I send any data the Kollmorgen drive replies with 0x7F.  If I send again, the drive replies with 0xFF.  This pattern repeats if I continue to send.  Unfortunately that is the only communication I've been able to get working.
    I have attached screen shots of the LabVIEW example I am using.
    Has someone communicated with these AKD drives using CANopen before?  If so, can you please give me an example of how to format my data.  My eventual goal is to get the motor position and send velocity commands.
    Thank you so much in advance!
    ...Mike
    Attachments:
    Capture.JPG ‏109 KB
    Capture2.JPG ‏41 KB

    Hi Mike_in_WI,
    What NI hardware are you using?
    It looks like the VI you have uses NI CAN VIs rather than CANOpen VIs. There is a CANOpen driver you can install (linked below), however the driver only supports our newer hardware (supported hardware is listed in the readme file).
    http://www.ni.com/download/ni-industrial-communications-for-canopen-1.0.3/4100/en/
    There is also the NI-CANOpen Library, which will work with older hardware and is likely what you will need to use since you have been using NI-CAN:
    http://sine.ni.com/nips/cds/view/p/lang/en/nid/202614
    It looks like you will likely want to use SDO protocol. The manual you posted lists the index and sub-index to use for specific commands using the SDO protocol. For example, one of the position commands has an index of 2050h and a sub-index of 0. The CANOpen library and driver have read/write VIs that take the index and sub-index as inputs and handles building the frames correctly behind the scenes.
    According to the manual, the message x700 + (device address) is for the node-guarding protocol, which monitors the status of all nodes (bootup, stop, etc). The response 0x7F indicates that the node is pre-operational. More information about node guarding can be found at the link below:
    http://www.canopensolutions.com/english/about_canopen/guarding_heartbeat.shtml
    Catherine B.
    Applications Engineer
    National Instruments

  • How to load 0XF0 into 1 byte ?

    Hi all,
    I am creating an array like this...
    private final static byte[] PSA325_ERR240_FAIL = {0x7e,0x0,0x1,0x5,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,(byte)0x82,
    (byte)0XF0,0x7e};
    its a 16 byte array...
    in the last but one byte which is 0xF0
    I want a value of 0xF0 i.e 240 to go in there....but if I don't cast it to a byte...I am not able to compile and if I am casting it to byte then it is going as -16 which I don't want..
    I want the value to go as 0XF0 or as 240....let me know if anyone knows the solution...
    all I want is how do I load a value of
    240 i.e 0XF0 in just one byte...???
    pls help!!!
    Satish

    Hi,
    I am clear to come extent but still not very clear as to how will I load 0xF0 into one of the indexes in the byte array..
    I mean if u look at my problem
    I want to load 0xF0 into one of the elements of the byte array...and if I am trying to load it as 0xFO the compilor doesnt accept as it is an int ..so I am casting it to byte..but ur solution of & it with 0XFF is not pocssible to in my case as
    again I cant use some tjhing like
    private final static byte[] PSA325_ERR240_FAIL = {0x7e,0x0,0x1,0x5,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,(byte)0x82,((byte)0xF0 & 0xFF),0x7e};
    as here again 0XFF is an int and cant be loaded into a byte array as an element....hope i have not confused you much..if u are clear..then please let me know the solution...
    my requirement is
    private final static byte[] PSA325_ERR240_FAIL = {0x7e,0x0,0x1,0x5,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,(byte)0x82,0xF0,0x7e}; in the last but one byte 0XF0 should go in and not as -16...how di I do it ?
    Satish

  • Big endian problem during readInt.

    What will happen if an int on a big endian platform is written to an socket using java.io.DataOutputStream's writeInt method
    and this int is then read by a little endian platform using java.io.DataInputStream's readInt method?
    coz the byte order is same,as a result the int in two platform will be different??
    How java achieve platform independent in this case?

    this is taken from the API docs
    writeInt
    public final void writeInt(int v)
    throws IOException
    Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the
    counter written is incremented by 4.
    Specified by:
    writeInt in interface DataOutput
    Parameters:
    v - an int to be written.
    Throws:
    IOException - if an I/O error occurs.
    See Also: FilterOutputStream.out
    The following is taken from the source code:
    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);
        } it takes the high byte and writes it first (by shifting 24 bits and ANDing with 0xFF) then does the
    same for all other bytes in the int (different shifts of course). You might have noticed that intel processors
    are little endian while the above code assumes that the int is big endian. Thats cos in java its all big
    endian.
    matfud

  • Read Pixel in image

    Hi, could anyone help me, i'm really upset in here..
    i try to read every pixel in my image, but what i got some number like this (-946523, -964323, and so on...) this is hexa right? and then i read some article, i got the answer like this :
    int pixel = -946523 & 0xff, what does it means?
    how can -946523 become 165?? i understand that 165 is the value of the pixel, right? but how can? how about the process? can anyone explain to me...
    Thanks a lot...

    Hi, could anyone help me, i'm really upset in here..
    i try to read every pixel in my image, but what i got
    some number like this (-946523, -964323, and so
    on...) this is hexa right? and then i read some
    article, i got the answer like this :
    int pixel = -946523 & 0xff, what does it
    means?
    how can -946523 become 165?? i understand that 165 is
    the value of the pixel, right? but how can? how about
    the process? can anyone explain to me...Pixels stored as integers have the following format:
    ARGB
    One byte of alpha information, a byte for red, a byte for green and a byte for blue.
    The byte represent a value from 0 to 255, where 0 means none of the component is present, and 255 means the full amount is present. For a fully opaque pixel (no tranparency), alpha is 255, which in hex is 0xFF. An integer in Java is a 32 bit signed value. The sign is carried in the high order bit. So, if you have a pixel packed as 4 bytes in an integer, and the pixel has an alpha value of 0xFF, the high order bit of the integer will alway be set, and the integer will be negative.
    A pixel value of -946523 in hex is 0xFFF18EA5. so, the pixel has an alpha value of 0xFF or 255, a red component of 0xF1 or 241; a blue component of 0x8E or 142; and a blue component of 0xA5 or 165.
    Your pixel in binary looks like this:
    1 1 1 1 1 1 1 1     1 1 1 1 0 0 0 1     1 0 0 0 1 1 1 0     1 0 1 0 0 1 0 1 
    ALPHA 24-31       RED  16-23          GREEN 8-15        BLUE 0-7So, say you want to get the alpha value, which is stored in the highest 8 bits, or bits 24 through 31. First, you need to shift those bits to the right until they are in the lowest 8 bits (0-7). This is done with the shift operator (>>).
    int pixel = -964323;
    int aShift = pixel >> 24;After this operation, the integer now looks like this:
    1 1 1 1 1 1 1 1     1 1 1 1 1 1 1 1     1 1 1 1 1 1 1 1     1 1 1 1 1 1 1 1
    Note that when you shift right in Java, the empty bits to the left are filled with ones. This is called sign extension, and it is a problem for us, because we want all zeros in the left bits, leaving just the alpha component bits unchanged. To do this, you mask, which is done use the AND operator (&). This operator takes two numbers and compares each bit. If the bits are both 1, a 1 is placed in the result, otherwise a zero is placed in the result. So, if we take the shifted integer above and mask it with 0xFF, it looks like this:
    1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 (shifted integer)
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 (mask 0xFF)
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 (result)
    The result is 0xFF, which is 255, which is the correct value for alpha.
    In code, this looks like:
    int a = aShift & 0xFF;This can all be done in one line as follows:
    int a = (pixel >> 24) & 0xFF;For the red component, we first shift 16 bits to the right, which gives us
    1 1 1 1 1 1 1 1     1 1 1 1 1 1 1 1     1 1 1 1 1 1 1 1     1 1 1 1 0 0 0 1  Once again, you mask with 0xFF and the result is:
    0 0 0 0 0 0 0 0     0 0 0 0 0 0 0 0      0 0 0 0 0 0 0 0      1 1 1 1 0 0 0 1which is 0xF1, or 241.
    In code:
    int r = (pixel >> 16) & 0xFF;Green is handled the same way, with a shift of 8 bits:
    int g = (pixel >> 8) & 0xFF;Blue is next, but what should be used for the shift value? Alpha was 24, red was 16, greeb was 8, which indicates that blue should be zero. In fact, if you use zero you will get the correct answer:
    int b = (pixel >> 0) & 0xFFbut not that the shift with 0 really doesn't do anything, so you can just use the mask, and get the right answer:
    1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 0 1 0 1 (pixel)
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 (mask)
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 (result)
    So, the blue pixel is 0xA5, or 165.
    In summary:
    int pixel = -964323;
    int a = (pixel >> 24) & 0xFF;
    int r = (pixel >> 16) & 0xFF;
    int g = (pixel >> 8) & 0xFF;
    int b = pixel & 0xFF;Jim S.

Maybe you are looking for

  • Animated GIF problem saving for web in CS6

    I made an animated gif in CS6 and trying to save it for the web. The duration of the animation is pretty long, about 44 seconds. After 17 seconds the animation stops while the saving was completed. How can I solve this problem? The file is too large

  • All clips from Canon 60D come out lagging

    I just recently bought both a Canon 60D and Final Cut Pro X for my Macbook Pro.  I have since tried repeatedly, in several ways, to upload my shot footage from that camera, and all of it lags and is choppy, at many points, having the frames dropped l

  • Input Field disabled in Web Dynpro Application

    Hi, I created an application with three input fields and created the corresponding context. When I start the wd app the input fields are disabled and can not be edited. The property enabled if this fields is true! I compared the context with other wd

  • How to send iPod back to get refurbished

    My i recently dropped my iPod in a bucket full of water and immediately took it out and set it aside to let it dry. After a week it would not turn on and my warranty has expired. Is there a way to send it back to Apple to let them fix it for a small

  • Oracle download bug

    i downloaded oracle 9i from the oracle site. the filename is A91514-01.zip. when i tried to extract it through winzip it is giving error. the error is , it is not able to extract the file "help.jar" due to internal errors.i want somebody to solve my