Bit permutation inside a byte array

Hi everyone,
I'm trying to implement DES algorithm, i want to permute specified bits inside an 8byte array.
I tought about extract every bits from the byte array inside a 64 byte array and then do the permutation.
But i don't see how to put these bits back into an 8byte array to return the result of encryption/decryption.
This is what i've done so far (inspired by sources i found on the internet) :
// extends 8 byte array into a 64 byte array
public static byte[] extendsByteArray(byte[] bytes) {
byte[] tab = bytes;
short len = (short)(desBlockSize * (short)8);
byte[] bits = new byte[len];
short i,j;
for (i = (short)(desBlockSize - (short)1); i >=0; i--) {
for (j = (short)0; j < desBlockSize; j++)
bits[--len] = (byte) ((tab[i] >> j) & 0x01);
return bits;
// 64 byte array to 8 byte array
public static byte[] transformByteArray(byte[] bits){
byte[] tab = bits;
byte[] bytes = new byte[desBlockSize];
short i,j = (short)0;
for ( i = (short)0; i < (short)8; i++){
bytes[i] = (byte)((bits[j] * (short)2^7) + (bits[j+(short)1] * (short)2^6)+
               (bits[j+(short)2] * (short)2^5) + (bits[j+(short)3] * (short)2^4)
               + (bits[j+(short)4] * (short)2^3) + (bits[j+(short)5] * (short)2^2)
               + (bits[j+(short)6] * (short)2) + (bits[j+(short)7]));
j +=(short)7;
return bits;
This implementation doesn't seems to work, do u have some ideas why it doesn't work or is there an easier solution to permute bits as i'm stuck with this fo the moment.
Thanks in advance for your answers,
Julien

If you are using JavaCard please do not use multiplications as you used in your code. Integer multiplications are very slow in any platform that does not implement them in hardware, and the virtual machine that runs in JavaCards usually does not do any optimizations or Just-In-Time compiling - simply interprets the codes. Memory and CPU power are at a premium in Java Cards. Even if your Java Card has a hardware multiplier, usually it is reserved for RSA operations - it is not available for general use for Java programs.
Instead of using x * 2 raised to the sixth power, use x << 6. It is faster and generates fewer bytecodes.

Similar Messages

  • Strange issue with POF: byte array with the value 94

    This is a somewhat strange issue we’ve managed to reduce to this test case. We’ve also seen similar issues with chars and shorts as well. It’s only a problem if the byte value inside the byte array is equal to 94! A value of 93, 95, etc, seems to be ok.
    Given the below class, the byte values both in the array and the single byte value are wrong when deserializing. The value inside the byte array isn’t what we put in (get [75] instead of [94]) and the single byte value is null (not 114).
    Pof object code:
    package com.test;
    import java.io.IOException;
    import java.util.Arrays;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    public class PofObject1 implements PortableObject {
         private byte[] byteArray;
         private byte byteValue;
         public void setValues() {
              byteArray = new byte[] {94};
              byteValue = 114;
         @Override
         public void readExternal(PofReader reader) throws IOException {
              Object byteArray = reader.readObjectArray(0, null);
              Object byteValue = reader.readObject(1);
              System.out.println(Arrays.toString((Object[])byteArray));
              System.out.println(byteValue);
              if (byteValue == null) throw new IOException("byteValue is null!");
         @Override
         public void writeExternal(PofWriter writer) throws IOException {
              writer.writeObject(0, byteArray);
              writer.writeObject(1, byteValue);
    Using writer.writeObjectArray(0, byteArray); instead of writer.writeObject(0, byteArray); doesn't help. In this case byteArray would be of type Object[] (as accessed through reflection).
    This is simply put in to a distributed cache and then fetched back. No EPs, listeners or stuff like that involved:
         public static void main(String... args) throws Exception {
              NamedCache cache = CacheFactory.getCache("my-cache");
              PofObject1 o = new PofObject1();
              o.setValues();
              cache.put("key1", o);
              cache.get("key1");
    Only tried it with Coherecne 3.7.1.3.
    Cache config file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
         <caching-scheme-mapping>
              <cache-mapping>
                   <cache-name>my-cache</cache-name>
                   <scheme-name>my-cache</scheme-name>
              </cache-mapping>
         </caching-scheme-mapping>
         <caching-schemes>
              <distributed-scheme>
                   <scheme-name>my-cache</scheme-name>
                   <service-name>my-cache</service-name>
                   <serializer>
                        <class-name>
                             com.tangosol.io.pof.ConfigurablePofContext
                        </class-name>
                        <init-params>
                             <init-param>
                                  <param-type>string</param-type>
                                  <param-value>pof-config.xml</param-value>
                             </init-param>
                        </init-params>
                   </serializer>
                   <lease-granularity>thread</lease-granularity>
                   <thread-count>10</thread-count>
                   <backing-map-scheme>
                        <local-scheme>
                        </local-scheme>
                   </backing-map-scheme>
                   <autostart>true</autostart>
              </distributed-scheme>
         </caching-schemes>
    </cache-config>
    POF config file:
    <?xml version="1.0"?>
    <pof-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.oracle.com/coherence/coherence-pof-config"
         xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-pof-config coherence-pof-config.xsd">
         <user-type-list>
              <!-- coherence POF user types -->
              <include>coherence-pof-config.xml</include>
              <user-type>
                   <type-id>1460</type-id>
                   <class-name>com.test.PofObject1</class-name>
              </user-type>
         </user-type-list>
    </pof-config>

    Hi,
    POF uses certain byte values as an optimization to represent well known values of certain Object types - e.g. boolean True and False, some very small numbers, null etc... When you do read/write Object instead of using the correct method I suspect POF gets confused over the type and value that the field should be.
    There are a number of cases where POF does not know what the type is - Numbers would be one of these, for example if I stored a long of value 10 on deserialization POF would not know if that was an int, long double etc... so you have to use the correct method to get it back. Collections are another - If you serialize a Set all POF knows is that you have serialized some sort of Collection so unless you are specific when deserializing you will get back a List.
    JK

  • How to add 16 bit message sequential number to the byte array

    hi
    iam trying to implement socket programming over UDP. Iam writing for the server side now.I need to send an image file from server to a client via a gateway so basically ive to do hand-shaking with the gateway first and then ive to send image data in a sequence of small messages with a payload of 1 KB.The data message should also include a header of 16 bit sequential number and a bit to indicate end of file.
    Iam able to complete registration process(Iam not sure yet).I dnt know how to include sequential number and a bit to indicate end of file.
    I would like to have your valuable ideas about how to proceed further
    package udp;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Sender  {
        protected BufferedReader in = null;
        protected FileInputStream image=null;
        protected static boolean end_of_file=true;
    /** pass arguments hostname,port,filename
    * @param args
    * @throws IOException
       public static void main(String[] args) throws IOException{
            DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[1]));
            boolean more_messages = true;
              String str1=null;
                * gateway registration
                try{
                     //send string to emulator
                    String str="%%%GatewayRegistration SENDER test delay 10 drop 0 dupl 0 bandwidth 1000000";
                    byte[] buff=str.getBytes();
                    InetAddress emulator_address = InetAddress.getByName(args[0]);
                    DatagramPacket packet = new DatagramPacket(buff, buff.length,emulator_address,Integer.parseInt(args[0]));
                    socket.send(packet);
                        // figure out response
                    byte[] buf = new byte[1024];
                    DatagramPacket recpack=new DatagramPacket(buf,buf.length);
                    socket.receive(recpack);
                   // socket.setSoTimeout(10000);
                    String str2=str1.valueOf(new String(recpack.getData()));
                    if(socket.equals(null))
                         System.out.println("no acknowledgement from the emulator");
                        socket.close();
                    else if(str2=="%%%GatewayConfirmation")
                    //     String str1=null;
                         System.out.println("rec message"+str2);
                    else
                         System.out.println("not a valid message from emulator");
                         socket.close();
                catch (IOException e) {
                    e.printStackTrace();
                      end_of_file = false;
         /**create a packet with a payload of 1     KB and header of 16 bit sequential number and a bit to indicate end of file
      while(end_of_file!=false)
          String ack="y";
          String seqnum=
           File file = new File(args[2]);                               
                    InputStream is = new FileInputStream(file);                 
            socket.close();
      private byte[] byteArray(InputStream in) throws IOException {
             byte[] readBytes = new byte[1024]; // make a byte array with a length equal to the number of bytes in the stream
          try{
             in.read(readBytes);  // dump all the bytes in the stream into the array
            catch(IOException e)
                 e.printStackTrace();
            return readBytes;
      

    HI Rolf.k.
    Thank you for the small program it was helpfull.
    You got right about that proberly there  will be conflict with some spurios data, I can already detect that when writing the data to a spreadsheet file.
    I writes the data in such a way, that in each line there will be a date, a timestamp, a tab and a timestamp at the end. That means two columns.
    When i set given samplerate up, that controls the rate of the data outflow from the device, (1,56 Hz - 200 Hz),   the data file that i write to , looks unorderet.
     i get more than one timestamp and severel datavalues in every line and so on down the spreadsheet file.
    Now the question is: Could it be that the function that writes the data to the file,  can't handle the speed of the dataflow in such a way that the time stamp cant follow with the data flowspeed. so i'm trying to set the timestamp to be  with fractions of the seconds by adding the unit (<digit>) in the timestamp icon but its not working. Meaby when i take the fractions off a second within the timestamp i can get every timestamp with its right data value. Am i in deeb water or what do You mean!??
    AAttached Pics part of program and a logfile over data written to file
    regards
    Zamzam
    HFZ
    Attachments:
    DataFlowWR.JPG ‏159 KB
    Datalogfile.JPG ‏386 KB

  • How to chnage number of bits in every packet of a byte array

    Hi I have an array of byte array of 1 and 0s. I would like to make sure every pack of 1 or 0s contains 8 number
    I can use this example to explain it better. Lets say I have this array
    111111110000000111111100000000
    As can be first pack of 0s and the second pack of 1s contain 7 bits. I would like to programaticaaly change it to 8 so the result should be
    11111111000000001111111100000000 
    As can be seen now evey pack of 1s or 0s contains 8 element . Could you please help me on this.A sample code would be great
    Many thanks

    Reshape array is your friend.Nevermind.  I just realized what you were going for.  Will need to rethink...
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    8x bits long.png ‏21 KB

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

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

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

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • Error when creating BufferedImage with IndexColorModel from a byte array.

    Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
    The color model I have is:
    int [] cmap = new int [numColors];
    cmap[i++] = 0xffa0f000;  /etc.
    new IndexColorModel(8, 22, cmap, 0, true,  transparentIndex,  DataBuffer.TYPE_BYTE );Thanks for your help
    -Ben
    Ps.
    I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
    [java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
    [java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    Code:
    byte[] pixelArray = (byte[]) getData_CHAR();                
    int width = 5120;
    int height = 3520;
    int numbytes = width*height;
    //create DataBuffer using byte buffer of pixel data.
    DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
    //prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
    int bitMasks[] = new int[]{0xf};
    SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
    //create a raster using the sample model and data buffer
    WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
    //generate 16-color model
    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    r[0] = 0; g[0] = 0; b[0] = 0;
    r[1] = 0; g[1] = 0; b[1] = (byte)192;
    r[2] = 0; g[2] = 0; b[2] = (byte)255;
    r[3] = 0; g[3] = (byte)192; b[3] = 0;
    r[4] = 0; g[4] = (byte)255; b[4] = 0;
    r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
    r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
    r[7] = (byte)192; g[7] = 0; b[7] = 0;
    r[8] = (byte)255; g[8] = 0; b[8] = 0;
    r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
    r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
    r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
    r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
    r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
    r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
    r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
    //create buffered image    
    ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
    BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
    ben_weisburd
    Message was edited by:
    ben_weisburd

    I had the same problem too.
    anyone found the solution for this problem?
    thanks
    Bruno Rabino
    When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
    Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
    Error creating module: ORA-01403: no data found (WWV-16042)
    When I use the table with the BLOB as master or in a form, it works fine.
    Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
    Portal version: 3.0.6.6.5
    null

  • Is there a memory limitation to byte arrays?

    Everyone,
    I have a huge(16MB) CMYK source file and I am trying to convert it to a sRGB /JPEG file and then compress it.
    When I try to read that file into a byte array it chokes and throws an OutOfMemoryException. Is there a way around this?
    thanks,
    Barat.

    The data looks something like this:
    CCCCC...MMMMM...YYYYY...KKKKK...
    CCCCC...MMMMM...YYYYY...KKKKK...
    where each letter represents one byte.
    For example, the first cyan byte has cyan information
    for 8 pixels -- each bit represents cyan or no cyan, etc.
    The point is to get this data in a viewable form on screen.
    Have tried increasing the heap to 256
    Of course the problem is in a large array that holds the output information, which is ~130M
    The original file size is 16M but this was expanded to eight times the size for the PixelInterleavedSampleModel
    where one data element (a byte in this case) represents one sample of a pixel
    There must be a better way - any suggestions?

  • Converting an integer to a byte array?

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

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

  • How to save a value in a byte array, retrieve it and display it?

    Hi,
    I am doing a project for my data structures class that involves saving a value (given in String format) in a byte array (our 'memory'). Initially I just tried casting character by character into the byte array and casting back to char[] for retrieval (using .toString() to return what's supposed to be the original string), but this did not work. I tried the .getBytes() method, applying it to the string and then trying to recover it by placing the contents of the 'memory' in a byte array and applying toString(), but that didn't work either. I looked a bit and found this class, CharsetEncoder and CharsetDecoder. I tried to use these but when I try the compiler tells me I cannot instantiate CharsetDecoder because it is an abstract class. At this point I'm at a loss as to what I can do. Is there any way to place a string in a byte array and then recover the string in it's original format? For example, I might save a value in my particular class of "456". But when I try to recover the value from my 'memory' i.e. the byte array, it comes out like [gnue@hnju.... or something similar. I need it to output the original string ("456").
    Below is my code as it is right now, for the methods setValue and getValue.
    Thanks!
    public void setValue(String value) throws InvalidValueException {
         //… stores the given value in the memory area assigned to the variable
              if(this.type.isValidValue(value)){
                   bytes = value.getBytes();
                   int i,j,k;
                   int l=0;//might be wrong?
                   int ad=address-(address%4);
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   if((address%4)+bytes.length-1<4){
                        for(i=address%4;i<address%4+bytes.length;i++)
                             reg.setByte(i, bytes[i]);
                        mem.setDataRegister(reg);
                        mem.writeWord(ad);
                   else if((address%4)+bytes.length-1>=4){
                        if(address%4!=0){
                             for(i=address%4;i<4;i++){
                                  reg.setByte(i, bytes);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        while(ad<address+bytes.length-(address+bytes.length)%4){
                             for(j=0;j<4;j++){
                                  reg.setByte(j, bytes[j+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        if((address+bytes.length)%4!=0){
                             mem.readWord(ad);
                             reg=mem.getDataRegister();
                             for(k=0;k<(address+bytes.length)%4;k++){
                                  reg.setByte(k, bytes[k+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                   else
                        throw new InvalidValueException("The value passed is not valid.");
         /** Gets the current value of the variable.
         @return current value converted to String
         public String getValue() {
              //… returns the current value stored in the corresponding memory area
              //… value is converted to String
              bytes=new byte[this.getType().getSize()];
              int i,j,k;
              int l=0;//might be wrong?
              int ad=address-(address%4);
              mem.readWord(ad);
              reg=mem.getDataRegister();
              if((address%4)+bytes.length-1<4){
                   for(i=address%4;i<address%4+bytes.length;i++)
                        bytes[i] = reg.readByte(i);
              else if((address%4)+bytes.length-1>=4){
                   if(address%4!=0){
                        for(i=address%4;i<4;i++){
                             bytes[i] = reg.readByte(i);
                             l++;
                        ad+=mem.WORDSIZE;
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   while(ad<address+bytes.length-(address+bytes.length)%4){
                        for(j=0;j<4;j++){
                             bytes[j+l] = reg.readByte(j);
                             l++;
                        ad+=mem.WORDSIZE;
                   if((address+bytes.length)%4!=0){
                        mem.readWord(ad);
                        reg=mem.getDataRegister();
                        for(k=0;k<(address+bytes.length)%4;k++){
                             bytes[k+l] = reg.readByte(k);
                             l++;
              return bytes.toString();

    You can certainly put it into a byte array and then construct a new String from that byte array. Just calling toString doesn't mean you'll automatically get a meaningful string out of it. Arrays do not override the toString method, so the use the one inherited from object.
    Look at String's constructors.

  • Displaying byte array PDF file in Portal

    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • Displaying Byte Array images in coldfusion

    This has been driving me crazy for a couple of days now.I
    have a Java class that returns pictures stored in a DB as a Byte
    Array.
    I am able to display the image but that is all i am able to
    do - I want to display the image name, description etc in a HTML
    before i display the actual image but i can't seem to find a way to
    do that.
    I tried using CFcontent as well and that did not help
    either.This is what i am currently doing - and all that displays on
    the screen is the picture and all content before the picture is
    nowhere to be seen.
    Picture Name: #variables.picName#
    Picture Description:#variables.picDescription#
    <cfscript>
    context = getPageContext();
    response = context.getResponse().getResponse();
    out = response.getOutputStream();
    response.setContentType("image/jpeg");
    response.setContentLength(arrayLen(session.picture));
    out.write(session.picture);
    out.flush();
    out.close();
    </cfscript>
    Any help will be greatly appreciated.

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Byte Array Copy

    Hello,
    I have a problem that I have to write code to address the issue of modem disconnections while copying data. The problem is that I have to programmactially dial modems and copy programs to a remote windows based system. The issue is that I sometimes get disconnected from the remote site and loose my copy progress. I want to be able to be able to break apart an executable into chunks and copy those chunks to the remote harddrive and if I get disconnect, I will re dial the connection and pick up where I left off so that I dont loose the time that I spent already copying the file.
    I am currently using this method for copying the executables across the dial up connection but need to modify it and to be honest I dont know how. I know I should stuff the executable into some sort of byte array, get the length of that array, and copy each byte array element to the harddrive; loop through the array until the copy is complete. If disconnection or "semaphore timeout" exception is thrown, redial the connection, read the bytes that are already written on the remote locations harddrive, compare the bytes to what is stored locally, and copy those bytes until complete.
    Here is the method that I am using. I understand that I could use NIO to do the copy and it would be faster but I dont want to have to make major changes. I have attempted to search google for answers but only can find methods like this. Which is basically what I have...
        public static boolean uploadPackage(String src,String dst) {
            try {
                InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dst);
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    System.out.println("WRITING BUFFER " + len + " " + in.read(buf));
                    out.write(buf, 0, len);
                in.close();
                out.close();
                return true;
            } catch (IOException e) {
                System.out.println("IOEXCEPTION " + e);
                return false;
        }

    Dukes are worthless.
    Do you have a question? I didn't see one.
    Why do you feel the need to put a bunch of byte arrays to disk? The file itself is ultimately a byte array. Why not just store a file that says what the last byte successfully transferred was. Probably it should also indicate the last file modification date, so you can see if the file has changed out from under you between transfers. Then you can just reload the file and resend the bits you need.
    For that matter, there must be a system that can transfer files in bits. I used to do this with uuencode and split on shell script. I wouldn't be surprised if rsync or something like it has support for something like this.

  • Byte array to png image conversion

    hi friends
    i am using a servlet using tomcat server to send multiple images to a client. i have stored all the images in a single byte array.and then encoded using base64. i am sending it to the client side and decoding it. when i extract the byte array and then try to convert it to image it shows an illegal argument exception.please help me?
    Pradeep

    dubwai
    Just looked at your code again. Did you mean int,not
    long?He wanted an unsigned int (which of course doesn't
    exist in Java) and if you look at his original code it
    was returning long.Well, it's not so much that I wanted an unsigned int, it's just that the data was stored as a 32 bit unsigned integer. Since the data represented numbers with a range of 0 to 2^32 - 1, the range exceeded what I could put in a Java int, thus I need to stuff it in a long - well, that was my reasoning anyway.
    Thanks for the nio tip, I'd not looked into that stuff and really should.
    Lee
    Thanks much for the code -

Maybe you are looking for

  • Can I suppress dialog outside script?

    I have a start up script that is used in cross-plattform production. It fixes the links of pictures. Works fine but the user still gets the warning message before the script does its work. If the document is opened by script I can suppress the dialog

  • Error while reversing the asset accounting document through t code AB08

    Hello All, i have one query where the user has scrapped the assets through T code ABAVN in the month Dec 2009 with doc date of Nov 30th 2009. Now he realised that the posting was wrong and he wants to reverse it in 1st of Jan 2010 with the t code AB0

  • Can't see my iPad PDF files in iTunes

    Since the new update I have a problem. I can see the PDF's in my iPad, but when I connect the iPad to my Mac I cannot see them in iTunes. I can see my old books and PDF's just fine, but when I tried to drop a new PDF file into the book category of my

  • Start Service at Boot

    Solaris 9 I need to start a service at boot time and cannot figure out where to place it. I Googled it but I could not find anything of real value. Thanks, DB

  • Pricing Error: Mandatory condition List price is missing

    Hi All, When an Order is created in ISA with a material with mandatory pricing condition is zero an error is raised. This is the right functionality. Due to this the order is not replicated into ECC. Is there any suggestion as to how this error messa