How write integer into a byte[]
How to use dataoutputstream to write an integer to one byte[];
http://java.sun.com/j2se/1.3/docs/api/java/io/DataOutputStream.html#write(int)
yourDataOutputStream.write(int)
Similar Messages
-
How convert integer into string
Hi,
I need to convert answer3 from double into String
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));Now the integer value is string but why i cannot get valur from my servlet to my web page
package net.mybizaid.isodms.servlet;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.mybizaid.isodms.*;
public class SPLDataInputServlet extends HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
System.out.println( "******************** Calculation Servlet ******************" );
String dij ;
String population_i ;
String population_j ;
String project_name = "";
String project_status = "";
double answer;
String handler = "";
String url = "";
double answer3;
String dij3 ="";
String tesside_luas_i ="";
String tesside_luas_j ="";
double answer2;
String dij2 ="";
String luas_i ="";
String luas_j ="";
String counter = "";
String i = "";
handler = request.getParameter( "handler" );
dij = request.getParameter("dij");
population_i = request.getParameter("population_i");
population_j = request.getParameter( "population_j");
project_name = request.getParameter( "project_name");
project_status = request.getParameter( "project_status");
dij2 = request.getParameter("dij2");
luas_i = request.getParameter("luas_i");
luas_j = request.getParameter( "luas_j");
dij3 = request.getParameter("dij3");
tesside_luas_i = request.getParameter("tesside_luas_i");
tesside_luas_j = request.getParameter( "tesside_luas_j");
HttpSession session = null;
session = request.getSession(true);
int cnt = counter != null && !counter.equals("") ? Integer.parseInt(counter) : 0;
int ii = i != null && !i.equals("") ? Integer.parseInt(i) : 0;
//Tesside
if (handler != null && !handler.equals( "" ) && handler.equals( "cal3" ))
try
System.out.println("The DIJ3 value is :"+dij3);
System.out.println("The tesside_luas_i value is :"+tesside_luas_i);
System.out.println("The tesside_luas_j value is :"+tesside_luas_j);
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));
String str = String.valueOf( answer3 );
System.out.println("The answer value is :"+str);
url = "/jsp/model/tessideAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//PotensiPasaran
if (handler != null && !handler.equals( "" ) && handler.equals( "cal2" ))
try
System.out.println("The DIJ2 value is :"+dij2);
System.out.println("The luas_i value is :"+luas_i);
System.out.println("The luas_j value is :"+luas_j);
answer2 = Double.parseDouble(dij2)/(1 + Math.sqrt(( Double.parseDouble(luas_i) / Double.parseDouble(luas_j) )));
System.out.println("The answer value is :"+answer2);
url = "/jsp/model/potensiPasaranAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//Reilly
if (handler != null && !handler.equals( "" ) && handler.equals( "add" ))
try
System.out.println("The DIJ value is :"+dij);
System.out.println("The population_i value is :"+population_i);
System.out.println("The population_j value is :"+population_j);
answer = Double.parseDouble(dij)/(1 + Math.sqrt(( Double.parseDouble(population_i) / Double.parseDouble(population_j) )));
System.out.println("The answer value is :"+answer);
url = "/jsp/model/reillyAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
doPost(request, response);
}//end doGet
public void dispatchErrorMsg(HttpServletRequest req, HttpServletResponse res,
String target, String message)
try
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
req.setAttribute("eshop.ErrMessage",message);
dispatcher.forward(req, res);
catch (Exception e)
System.err.println( e.getMessage() );
}//end class -
How to convert a integer into bytes!!!
I am trying to pack the length of the data transamitted over a stream into 2 bytes (Each byte is a unsigned char in terms of 'C' language). When i am using the bytes in java any value greater than 127 is a negative number (I understand the very definition of 'byte' in java), my question is how to pack the length of the data the 'C' way still following Java rules??
Example :: Length of the data is 168 say!
the 2 bytes would be 0x00, 0x80 (the respective ascii values would be NULL, P) but with Java i get some thing different as we know??
byte 1 = 00 and byte 2 = -88 ( i am not sure what would be the ascii equivalent of this??)
Please help!For what it's worth:package ca.adaptor.util;
* $Id: ByteUtil.java,v 1.6 2003/03/28 18:24:47 mike Exp $
* Copyright (c) 2002 by Michael Coury
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* @author Michael Coury (mdc)
* @created Sep 20, 2002
* @version $Revision: 1.6 $, $Date: 2003/03/28 18:24:47 $
public final class ByteUtil {
private static final int __NUM_BYTES_IN_LONG_ = 8;
private static final int __NUM_BYTES_IN_INT_ = 4;
private static final int __NUM_BYTES_IN_SHORT_ = 2;
private static final int __NUM_BITS_IN_BYTE_ = 8;
private static final long __BYTE_MASK_ = 0xFF;
/** PRIVATE CONSTRUCTOR */
private ByteUtil() {}
///// ENCODE /////
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final long aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_LONG_];
for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final int aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_INT_];
for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final short aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_SHORT_];
for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final double aNum) {
return toBytes(Double.doubleToRawLongBits(aNum));
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final float aNum) {
return toBytes(Float.floatToRawIntBits(aNum));
///// DECODE /////
* Converts a byte array representing a long back to a long
public static final long toLong(final byte[] aNum) {
try {
long ret = 0L;
for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++) {
ret += ((long) aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for long. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_LONG_);
* Converts a byte array representing an int back to an int
public static final int toInt(final byte[] aNum) {
try {
int ret = 0;
for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for int. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_INT_);
* Converts a byte array representing a short back to a short
public static final short toShort(final byte[] aNum) {
try {
short ret = 0;
for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for short. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_SHORT_);
* Converts a byte array representing a double back to a double
public static final double toDouble(final byte[] aNum) {
return Double.longBitsToDouble(toLong(aNum));
* Converts a byte array representing a float back to a float
public static final float toFloat(final byte[] aNum) {
return Float.intBitsToFloat(toInt(aNum));
///// SHIFTING /////
public static final byte shiftRightUnsigned(final byte b, final int shift) {
return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) ((b & 0xFF) >>> shift);
public static final byte shiftRight(final byte b, final int shift) {
return (byte) (b >> shift);
public static final byte shiftLeft(final byte b, final int shift) {
return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) (b << shift);
} -
How do i covert an image in J2ME into an byte array ?
Can anyone help to show me the way to convert an image into a byte array ?
Thanks early reply appreciated.Hi! I�m developing an application to be installed in two devices. My problem is that i want to send an image: I can receive it with createImage(InputStream ip), but how can i send it with OutputStream? it needs a byte array (method write), how can i convert an image into a byte array?is there any other solution? like send it as a string...
Thanks -
How can I load a pdf-file into a byte[]?
Hello,
I would like to load a PDF-File into a byte-Array. How can I do this? The standard Streams shouldn't work because this can't be converted into characters. Can it? So, what does work?
Any idea?
Bye,
WolfangWhy would someone not do:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = new FileInputStream("foo.pdf");
byte[] buf = new byte[4096];
for(int len=-1;(len=is.read(buf))!=-1;)
baos.write(buf,0,len);
is.close();
baos.flush();
baos.close();
buf = baos.toByteArray(); // Here are you bytes!You don't need to know the exact size, let ByteArrayOutputStream do it for you. Streams are generally for bytes, Readers/Writers generally for characters. Why exactly did you say: ``The standard Streams shouldn't work because this can't be converted into characters?'' -
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 -
How to activate another worksheet in excel file and write data into it
Hi,
I am writing an automation program to collect test data and write the data to an excel file.
The excel file has several worksheets and now I can only write data to one sheet. Can anyone please let me know how to activate another worksheet and write data into it? Thank you very much.You can do a search in the Example Finder for more Excel VIs.
They will give you a clearer idea of how to go about doing things in the way you need.
- Partha
LabVIEW - Wires that catch bugs! -
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!!!
SatishHi,
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 -
How to read an inputStream in UTF-8 into a byte array.
Hi, Java version is 1.4.2. If inputStream.read() is used to read the bytes into a byte array, is it guarenteed that UTF-8 chars are correctly transferred into byte array? Or should we use InputStreamReader? An example would be a great help.
Thanks in advance.I would like to send a byte array read from InputStream to another app where they are converted to UTF-8. In brief
-Read input stream which comes in UTF-8 into a byte array
-Send byte array to another app which will convert it into UTF-8 characters -
How do I go from byte to int?
I am writing a program which reads a file in, transforms it into a byte array and then extracts information out of the byte array. One of these bits of information is an integer. I am having great trouble actually transforming the byte[] containing the bytes for the integer actually into the integer!
I've Googled and looked around forums and I'm just not sure why it's not working. :s
This is what I have so far:
private int bytesToInt(byte[] b) {
int bLen = b.length;
System.out.println("length: " + bLen);
int result;
switch (bLen) {
case 1: result = (int)b[0] & 0xFF; break;
//case 2: return b[0]
default: result = 999; break;
} // switch
return result;
} // bytesToInt()When i run it at the moment, with the integer 5 in the file, it returns 53 instead.. Any help would be much appreciated!I seem to be going round in circles with this!! I've tried various ways and i'm just not getting it. :s
This is what i've tried:
private int bytesToInt(byte[] b) throws IOException {
// takes the bytes specifying the win amount, casts to char and parses to int
int bLen = b.length;
char[] ch = null;
int result = 0;
// can take numbers up to 999
switch (bLen) {
case 1: ch[0] = (char)(b[0] + '0');
result = Character.digit(ch[0], 10);
break;
// case 2: ch[0] = (char)(b[0] + '0'); ch[1] = (char)(b[1] + '0'); break;
// case 3: ch[0] = (char)(b[0] + '0'); ch[1] = (char)(b[1] + '0'); ch[2] = (char)(b[2] + '0'); break;
default: result = 0; break;
} // switch
return result;
} // bytesToInt()which gave me the error:
Exception in thread "main" java.lang.NullPointerException
at lod.LODMapLoader2.bytesToInt(LODMapLoader2.java:112)
at lod.LODMapLoader2.getWinAmount(LODMapLoader2.java:99)
at lod.LODMapLoader2.main(LODMapLoader2.java:181)
Vanessa-Clarkes-MacBook:src vrc20$ javac lod/LODMapLoader2.java
Vanessa-Clarkes-MacBook:src vrc20$ java lod/LODMapLoader2 testFile
and so then i tried to simplify it and only consider if i was to be given one int..
private int bytesToInt(byte[] b) throws IOException {
// takes the bytes specifying the win amount, casts to char and parses to int
int bLen = b.length;
char ch;
int result = 0;
// can take numbers up to 9
ch = (char)(b[0] + '0');
result = (int)ch - '0';
return result;
} // bytesToInt()This ended up giving me 53 again. I'm feeling slightly frustrated.. What have I missed? -
Dear Experts,
Please help me in checking why virtual bytes in perfmon is taking more than memory we allocated.
OS
Windows Server 2003 R2 Enterprise x64 Edition Service Pack 2 (build 3790)
ORACLE
Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
PL/SQL Release 11.1.0.6.0 - Production
CORE 11.1.0.6.0 Production
TNS for 64-bit Windows: Version 11.1.0.6.0 - Production
NLSRTL Version 11.1.0.6.0 - Production
Total RAM on box is 8G
Page File
Windows virtual memory equal on C,D,E,F drives is set to 12273M and allocated now is 11262M
LPENABLED is not set
SQL> show parameter pga_
pga_aggregate_target 0
SQL> show sga
Total System Global Area 5344731136 bytes
Fixed Size 2114736 bytes
Variable Size 4630514512 bytes
Database Buffers 671088640 bytes
Redo Buffers 41013248 bytes
SQL> show parameter memory
hi_shared_memory_address 0
memory_max_target 5G
memory_target 5G
shared_memory_address 0
SQL> show parameter sga
lock_sga FALSE
pre_page_sga FALSE
sga_max_size 5G
sga_target 0
Question :
Why oracle.exe is taking 8G virtual; bytes, memroy target can not go beyond 5G. How to minimized the virtual byte in perfmon
Thanks in advance your time and help.John, Thanks for the reply.
Please find the output of query
SQL> select pool,sum(bytes) from v$sgastat group by pool;
POOL SUM(BYTES)
915543216
java pool 67108864
streams pool 268503944
shared pool 2147494008
large pool 67108864
SQL>
SQL> select * from v$pgastat;
NAME VALUE UNIT
aggregate PGA target parameter 671088640 bytes
aggregate PGA auto target 147564544 bytes
global memory bound 104857600 bytes
total PGA inuse 533962752 bytes
total PGA allocated 810819584 bytes
maximum PGA allocated 1244466176 bytes
total freeable PGA memory 90243072 bytes
process count 450
max processes count 588
PGA memory freed back to OS 1.9883E+10 bytes
total PGA used for auto workareas 28210176 bytes
maximum PGA used for auto workareas 39973888 bytes
total PGA used for manual workareas 0 bytes
maximum PGA used for manual workareas 531456 bytes
over allocation count 7
bytes processed 2.6307E+10 bytes
extra bytes read/written 0 bytes
cache hit percentage 100 percent
recompute count (total) 72720
19 rows selected.
SQL>
SQL> show parameter _target
NAME TYPE VALUE
archive_lag_target integer 0
db_flashback_retention_target integer 1440
fast_start_io_target integer 0
fast_start_mttr_target integer 0
memory_max_target big integer 5G
memory_target big integer 5G
pga_aggregate_target big integer 0
sga_target big integer 0
SQL> sho parameter sga_max
NAME TYPE VALUE
sga_max_size big integer 5G -
How to track no of bytes transferred
Hi there,
how to track no of bytes transferred
while downloading a file using java servlets.
please note that i am not writing any client side application like applet...
Hence I want to track no of bytes transffered to client end from my server (using servlets)
Please kindly help me out as soon as possible.
awaiting the solution immediately.
thanks,
venkat//the following is the code what i have written in my servlet.
res.setContentType(MIME); // I hava parameterised the MIME tag
OutputStream out=res.getOutputStream();
int counter=0;
File f1 = new File("c:/x.pdf");
//int k=(int)f1.length();
fis = new FileInputStream(f1);
byte[] buffer=new byte[fis.available()];
fis.read(buffer);
for(i=0; i<buffer.length; i++)
try
counter=i+1; //getting the number of bytes got transferred
out.write(buffer,i,1); //write to client's directory
catch(IOException ex)
System.out.println("exception while download="+ex.getMessage());
downloaded=true;
if(counter!=buffer.length)
download_error="Not Downloaded";
download=false;
//while executing the above servlet, the servlet prompts for a save as dialog (without file extension, please note I have specified the MIME tag also).
Now the client is entering the file and clicking save
In between he cancels and file is not downloaded to the client's directory.
Now the counter length should not match with the buffer.length, but it is matching exactly and stating that the file has been downloaded properly.
I hope you would have understood my problem.
Also note that I dont have any client side application to monitor the download.
Please let me know how to solve the problem as soon as possible
expecting your reply at the earliest thanks. -
Uploading file to the servelet and write directly into database
i want client to upload file to the server (using servlet for that) and i just don't want to store it to the hard disk, but i want to write it
into the the ms sql database (that i m using).
TIAHere is a good site for learning how to upload a file using a servlet:
http://www.servlets.com/cos/index.html
Once you get the file in the servlet you shouldn't have any problem storing it to a DB. -
How to save the audio bytes in a file
I am capturing the audio from microphone.I write the audio data as bytes to other clients.How can i save the bytes in a wav file and it can be played in future?Please help.I want to write the audio bytes in a wav file
get sample source code from
http://javasolution.blogspot.com/2007/04/record-and-save-audio-using-java.html -
How to use ImageIcon's byte[] constructor?
As subject states
I've tried many many times and I just cna't get it. I can get it working using ImageIcon's String (filename) constructor, but the application I'm developing for requires the use of a byte[] array.
Could someone please share some code that reads data from an image file (jpg preferably) and converts it into an array of bytes and uses that to (successfully!) create a working ImageIcon?
ThanksIt should work to use a BufferedInputStream instead of BufferedReader and InputStreamReader. I tried this test code.
public static void main(String[] args) throws Exception {
ArrayList byteList=new ArrayList();
byte[] inbytes={12,-127,-126,-2};
ByteArrayInputStream bas=new ByteArrayInputStream(inbytes);
BufferedInputStream br=new BufferedInputStream(bas);
byteList.add(new Integer(br.read()));
byteList.add(new Integer(br.read()));
byteList.add(new Integer(br.read()));
byteList.add(new Integer(br.read()));
byte[] byteArray = new byte[byteList.size()];
for(int i=0;i<byteArray.length;i++) {
byteArray=(byte) (((Integer) byteList.get(i)).intValue());
System.out.println(byteArray[i] );
It displays the same values as the original inbytes values. When I tried the same code except using InputStreamReader and BufferedReader, I did not get the original inbytes values. There's character encoding with a Reader that may change the values. Streams give the raw data.
Maybe you are looking for
-
Hello, I hope you can help me out with a Java excercise I am working on. I am using "Learn to Program with Java by John Smiley. It involves error checking to see if the user clicks cancel without sending a required string or sending an empty string o
-
How can i create stored procedures dynamically?
I have tried to create a stored procedure building a string with the PL/SQL code needed to create the procedure. If i run the code using SQL+ works fine, but using the following code: Public Sub CreateStoredProcedure() Dim strSql As String strSql = "
-
Event Structure's value change, not detecting changes when tabbing thru array of clusters
Hi! I have an array of clusters (int, int, string, int) control, and want to detecting changes made to the it. I used the Event Structure's value change case on the array, it works excellent except that it'll only detect the changes when you click
-
I read that certain fonts may not be embedded in a pdf file. Will Adobe Reader prevent this from happening automatically?
-
how do I do this?