Storing a short variable in a byte array of length 2
I was wondering if there was a way to store a short in a byte array? Where the first byte is stored in the first element and the second byte is stored in the second element.
vr_84 wrote:
How would I access the first and second byte of the short?I'm just gonna post this...
short n = someShort();
byte[] littleEndian = new byte[] { (byte)n, (byte)(n >>> 8) };
byte[] bigEndian = new byte[] { (byte)(n >>> 8), (byte)n };I haven't compiled or tested it, but that should work.
EDIT: Too slow :-)
Similar Messages
-
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(); -
How to put a String into a byte array
How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David
javadocs for String
getBytes
public byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Returns:
The resultant byte arraySince:
JDK1.1 -
Sending a byte array of greater length than the APDU data buffer
Hello again, I am now trying to send a byte array of length 480 from the smart card. I've tried setting the outgoing length to 480 first but as i had expected, this threw an exception. Then i tried setting it to 240 and then copying from the array into the apdu buffer in two halves and calling sendBytes() twice, but this only worked the first time - it send the first 240 bytes and then threw an error. Is it possible to do what i am trying to accomplish? If so, what am I missing?
the applet:
H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src\com\sun\javacard\samples\photocard
the client:
H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src_client\com\sun\javacard\clientsamples\photocardclient
here is the code i have used to store large data on card. maybe it will help you.
i send a series of apdu, where each contains 128 bytes of data (all apdu must have the same length - except the last).
public void writeAPDU(APDU apdu)
byte[] buffer = apdu.getBuffer();
short lc = (short)(buffer[ISO7816.OFFSET_LC]&0xFF);
short p1 = (short)(buffer[ISO7816.OFFSET_P1]&0xFF); // counter
short p2 = (short)(buffer[ISO7816.OFFSET_P2]&0xFF); // length of send data
short offset = (short)(p1 * p2); // calculate the offset
apdu.setIncomingAndReceive();
// check for first apdu (contains the total size of data)
if(p1 == 0 && p2 == 0)
short l = Util.getShort(buffer,ISO7816.OFFSET_CDATA);
data = new byte[l];
else
// store bytes in array
Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, data, offset, lc);
} -
Tips for shaving a few bytes off a byte array?
Hi, before you give me the standard solution using Inflator and Deflator, Im doing this on a J2ME device (of which there is no solution already implemented for both compression and decompression).
I have a few byte arrays of length 150-300 bytes and just want to squeeze things all tighter if possible. The header information for decoding them should be stored in the resulting byte[] array also.
I know storing a huffman tree would probably be too large for this so I just want suggestions for any tiny things that can be done (ie looking for repetitions of bytes or nibbles in the array)
Thanks in advance!how large a header would I have to store in the byte
array? The arrays are very small and this header data
must be included in them!No header at all -
Imageicon created from byte array gives -1 height and -1 width...
Hi,
when I am trying to create an imageicon object from byte arrays the length and width of the object are coming to be -1.So I am unable to resize the image..
This is happening for only few images, most of them are working fine and I can resize it...
What possibly could be wrong??
ImageIcon imageIcon = new ImageIcon(pImageData) where pImageData is bytearray..
but I am getting imageIcon.getIconWidth()=-1
and
imageIcon.getIconHeight()=-1
Can anyone help???es5f2000 wrote:
I'm not sure if this is related, but I believe that images which are not currently being rendered return -1, -1 as their size.It is not even correct, so I'm confident it is not related.
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.net.URL;
class TestIconSize {
public static void main(String[] args) throws Exception {
Image image = ImageIO.read( new URL(
"http://forums.sun.com/im/silver-star.gif") );
ImageIcon imageIcon = new ImageIcon( image );
System.out.println( "Width: " + imageIcon.getIconWidth() );
System.out.println( "Height: " + imageIcon.getIconHeight() );
}Output.
andrew@pc1:/media/disk/projects/numbered/all$ java TestIconSize
Width: 16
Height: 16
andrew@pc1:/media/disk/projects/numbered/all$ The post after yours seems of even more dubious quality. For those (and other) reasons, I second Darryl's call for an SSCCE. -
Displaying the .png image stored in an byte array
Hi,
I have to download an .png image from a server and i have to store it in a byte array and i have to display this byte array in another servlet. I have written the code to get the image from the remote server in a java class. The java class returns the byte array of the image and i have to display that in an servlet.
If anybody has the code or any refrence to refer please help me..
Thanks & Regards
-SandeepI have pasted code for servlet's doGet method which writes image data...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException
HttpSession session = request.getSession(); //taking httpsession
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream(); //taking outputstream of response
if (rtn.getErrorCode() == 0)
//this will actually write image file data from where it is being called
//byte array will contain image data, please load your image into below byte array variable
byte[] b = new byte[100];
out.write(b);
out = null; //making null
session = null; //making null
In other servlet, write <img> tag and specify its src attribute to the "name of servlet where u have pasted above code" ..
Regards,
Nikhil -
How do I store an Int, a short, and multiple bytes from file in byte array
I'm attempting to do this for a project but can't figure out how to store the three values in one byte array. This is what i've tried
public void send(byte[] input)
// TODO
ByteArrayInputStream bais = new ByteArrayInputStream(input);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
byte[] pData = new byte[100];
try {
dos.writeShort(checkSum);
dos.writeInt(nextSeqNum);
pData=baos.toByteArray();
bais.read(pData);
} catch (IOException e) {
DatagramPacket dgp = new DatagramPacket(pData, pData.length);When i set pData=baos.toByteArray() it changes the size and then stops me from being able to read the other 94 bytes into the array to send. Any ideas?You don't need the ByteArrayInputStream at all.
dos.writeShort(checkSum);
dos.writeInt(nextSeqNum);
dos.write(input);
pData = baos.toByteArray();
When i set pData=baos.toByteArray() it changes the sizeNo, it makes it refer to a new byte[] array containing what you've written to the BAOS. That's what it's supposed to do. -
Send byte array argeument from pl/sql to java stored procedure?
I have a java method that accepts an argument of type byte[].
I want to define a call specification so that it can invoked from a sql statement.
The Java Developer's Guide show how to map SQL data types to java types and classes, but it is unclear if I can map a SQL data type to an array.
Does anyone know which SQL type to use to map to a byte array?
I'm using Oracle 10.2, thus jvm 1.4.2.As soon as I posted this question, I saw the RAW to byte[] mapping listed in the documentation. How did I overlook it? Anyway, that what I needed.
-
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. -
Problem in reading/writing byte array in Access database! PLEASE HELP!!
Hi,
I want to store a signature, which is in form of a byte array, in OLE Object field in MS Access database. I want then to retrieve this signature and verify it. The problem is that the retrieved byte array is not identical to the stored (original) one, and therefore, verifying the signature fails! Any help would be much appreciated as I can't proceed in my project without solving this problem. Here is the code to do the above mentioned functionality:
//This part stores the signature (VT) in the table TTPTrans
try
{ con = connect();
ps = con.prepareStatement("UPDATE TTPTrans SET VT = ?, SigVT = ? WHERE TransID = ?");
ps.setBinaryStream(1, new ByteArrayInputStream(vt), vt.length);
ps.setBinaryStream(2, new ByteArrayInputStream(sigvt), sigvt.length);
ps.setString(3, tID);
ps.executeUpdate();
ps.close();
con.close();
catch (Exception e)
{ System.err.println(e.getMessage());
e.printStackTrace();
//This part retrive the signature from the table in the byte array o1:
ResultSet result;
byte[] o1 = null;
byte[] o2 = null;
try
{ con = connect();
Statement statement = con.createStatement();
result = statement.executeQuery("SELECT VT, SigVT" +
" FROM TTPTrans" +
" WHERE TransID = " + "'" +
transID + "'");
while (result.next()) {
o1 = result.getBytes("VT");
o2 = result.getBytes("SigVT");
statement.close();
con.close();
catch(Exception e)
{ System.err.println(e.getMessage());
e.printStackTrace();
}In the following code, I use a ASN1SDSSSignature class, which is a subclass that I created from the Siganture class, to create and verify an SDSS signature. The ASN1SDSSSignature has two ASN1Integer class variables:
signcryption = token.getSigncryption();
sig.initVerify(ttpCert);
sig.update(receivedVT);
boolean verified = sig.verify(receivedSigVT);
if(!verified)
System.err.println("TTP signatire on received token invalid. ");
notify()
return;
Where receivedVT and receivedSigVT are the byte arrays retrieved from th database. The following exception is thrown when I run the application:
ASN1 type mismatch!
Expected: codec.asn1.ASN1Integer
In: ASN1SDSSSignature
At index 0
Got tag: 4 and Class: 0
I hope this would clarify the situation and thanks in advance for any comments you may post. -
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 save Byte Array of raw data into JPEG image.
Hello!
I have a image and I stored its data as byte array as
bimage = bitmap1.getRawData();
now I have Byte[] bimage, I want to save it as .jpeg image.
and show that image..............the short way is this:
ImageIO.write(bimage, "jpeg", new File("image.jpg"));
Where you use the original Image object... but it has to be a java.awt.image.RenderedImage (which a java.awt.image.BufferedImage is). So this method would come in handy.
public static BufferedImage getBufferedImage(Image img) {
// if the image is already a BufferedImage, cast and return it
if((img instanceof BufferedImage) && background == null) {
return (BufferedImage)img;
// otherwise, create a new BufferedImage and draw the original
// image on it
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}If the byte array you have is raw image data, then you can look at the javax.imageio package and see what you can do with those classes. -
Please show me someone an short example to store an byte[] as a blob and
restore it.
(.java and .jdo files).
Thank you,
MihaiMy configuration is:
- DB : MySql 3.23.38
- Kodo : 2.2.6 (also 2.3.0 beta)
- i use JBuilder Kodo open-tool , another problem is 2.3.0 JBuilder Kodo
open-tool which is not working for a project previous configured with 2.2.6
(=> kodo.properties).
- another thing do say is "double" values stored in db. For example if i put
2.0 double value in db , then when i read this value from db, a 1.99999
double value is returned (but i read that bug also in your manual).
(thank you for your tip)
Abe White <[email protected]> wrote in message
news:agmtu0$o3e$[email protected]..
What database are you using? Let me know and I'll log this as a bug. Thereason it's happening is that we use ObjectOutput.writeObject() to write
blobs to the database, even if they're already a byte array. And as we read
them back in, it appears that in some databases we don't properly use
readObject() to get rid of the extra bytes serialization inserts. To get
around the bug temporarily, you could do this yourself (i.e. bytes =
(byte[]) new ObjectInputStream (new ByteArrayInputStream (bytes)).readObject
> -
How Do I Load An Animated GIF Into PictureBox Control From Byte Array?
I'm having a problem with loading an animated GIF int a picturebox control in a C# program after it has been converted to a base64 string, then converted to a byte array, then written to binary, then converted to a base64 string again, then converted to
a byte array, then loaded into a memory stream and finally into a picturebox control.
Here's the step-by-step code I've written:
1. First I open an animated GIF from a file and load it directly into a picturebox control. It animates just fine.
2. Next I convert the image in the picturebox control (pbTitlePageImage) to a base64 string as shown in the code below:
if (pbTitlePageImage.Image != null)
string Image2BConverted;
using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
using (MemoryStream ms = new MemoryStream())
bm.Save(ms, ImageFormat.Jpeg);
Image2BConverted = Convert.ToBase64String(ms.ToArray());
GameInfo.TitlePageImage = Image2BConverted;
ms.Close();
GameInfo.TitlePageImagePresent = true;
ProjectNeedsSaving = true;
3. Then I write the base64 string to a binary file using FileStream and BinaryWriter.
4. Next I get the image from the binary file using FileStream and BinaryReader and assign it to a string variable. It is now a base64 string again.
5. Next I load the base64 string into a byte array, then I load it into StreamReader and finally into the picturebox control (pbGameImages) as shown in the code below:
byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Position = 0;
pbGameImages.Image = Image.FromStream(memTitlePageImageStream, true);
memTitlePageImageStream.Close();
memTitlePageImageStream = null;
TitlePageImageBuffer = null;
This step-by-step will work with all image file types except animated GIFs (standard GIFs work fine). It looks like it's just taking one frame from the animation and loading it into the picturebox. I need to be able to load the entire animation. Does any of
the code above cause the animation to be lost? Any ideas?There is an ImageAnimator so you may not need to use byte array instead.
ImageAnimator.Animate Method
http://msdn.microsoft.com/en-us/library/system.drawing.imageanimator.animate(v=vs.110).aspx
chanmm
chanmm
Maybe you are looking for
-
Error in connecting to database using a datasource in a jsp file
Dear SDN's, I have a program which retreives Data from the Employee table and displays on portal page. What i have done is, I have created a pageprocessor component, with 2 jsp files one is for data insert and other is for retriving the data from the
-
Folder view settings not retained in Leopard
Anyone else seen this problem ? I like to have different folders with different view settings - some icon, some list, and now some coverflow. But, it doesn't retain these settings, it just reverts to whatever view I was looking at last, and applies t
-
Transaction launcher opens empty transaction IC_LTXE in target system
Hello, we've got an issue with the transaction launcher. We want to open an ecc transaction. Logical system in TCRMS_IC_CROSS_SYS is defined as: http://<server>:<port>/sap/bc/gui/sap/its/webgui/!?transaction=IC_LTXE&okcode=ICEXECUTE Rfc connection wi
-
HOW DO I SAVE A VID VIA MMS?
help! i cant seem to save a video that was sent to me via multi media message! i've tried everything but nothing lets me go to see the video or save it!?
-
Two camera distortion correction images and how to get rid of
I noticed when I was using the Correct Camera Distortion filter that two images were created after I finished. The edges of the bottom image were peeking out from under the top, duplicate image. Not a problem until I went to copy and paste from image