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);
}

Similar Messages

  • How to convert an Integer to byte[] without lose data?

    How to convert an Integer to byte[] without lose data?

    I use the following to convert any java Object to a byte array
    public static byte[] getBytes(Object obj) throws java.io.IOException
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            bos.close();
            byte [] data = bos.toByteArray();
            return data;
    }

  • How to convert Doc file into image

    hello frnds
                     Can any body guide me how to convert doc file into image and show into swf loader.
    actually i have to convert doc files into swf files in runtime so that i have to use this flow.
    is it possible to convert doc file into byte array and than convert into image.
    Thanks And Regards
        Vineet Osho

    You can convert any DisplayObject to byeArray using this function ImageSnapshot.captureBitmapData().getPixels()

  • To convert an integer into word

    How do I convert an integer into word in labview. That is for example my input is 100 and  I want "one hundred" as output. I am using Labview 2011.Please help me.............

    Quotient and remainder with an word-list and exponent with a exponent word-list.
    e.g. 123 = x
    log 123 = 2.1 ==> 2 rounded down = y
    While{
      quotient(x-10^y;10)=z
      Get wordlist(z)
      Get exponentlist(y)
      x=x-10^y
      y--
    Then it'll get a little messy with 11-20.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • How to convert word doc into pdf - which product of adobe i need to use- what upgrades - am a newbie

    How to convert word doc into pdf - which product of adobe i need to use- what upgrades - am a newbie -  simple answers please - Thanks in advance.

    @Pipeline2007 - which version of Microsoft Office have you got? Older versions of Acrobat aren't compatible with the latest versions of Office, see this link for info:
    http://helpx.adobe.com/acrobat/kb/compatible-web-browsers-pdfmaker-applications.html

  • How to convert jpeg files into word

    How to convert jpeg files into Word

    Hi Eugene,
    I don't think you can convert an image to a Word document, but you could place the JPEG into a Word document using the Insert > Object command in Word.
    For other questions relating to Word, you will probably have more luck getting an answer if you post on the Microsoft forums (we can help if you're using Acrobat, or another Adobe product, but you'll find the Word experts on the Microsoft forums.)
    Best,
    Sara

  • How to convert Date format into day in ssrs reports?

    Hi
    How to convert date format into day?
    10/01/2010 as like Monday like that?

    =weekdayname(datepart("w",Fields!mydate.Value))
    -Vaibhav Chaudhari

  • How to convert system Date into DD-MMM-YYYY Format

    hi friends,
    please help me How to convert system Date into DD-MMM-YYYY Format.
    Regards
    Yogesh

    HI..
    data: w_dt(11) type c,
             w_month(2),
             w_mon(3).
    w_month = p_date+4(2). **p_date = given date**
    case w_month.
    when '01'.
    w_mon = 'Jan'.
    when '02'.
    w_mon = 'Feb'.
    when '03'.
    w_mon = 'Mar'.
    when '04'.
    w_mon = 'Apr'.
    when '05'.
    w_mon = 'May'.
    when '06'.
    w_mon = 'Jun'.
    when '07'.
    w_mon = 'Jul'.
    when '08'.
    w_mon = 'Aug'.
    when '09'.
    w_mon = 'Sep'.
    when '10'.
    w_mon = 'Oct'.
    when '11'.
    w_mon = 'Nov'.
    when '12'.
    w_mon = 'Dec'.
    endcase.
    Now...
      concatenate p_date6(2)  '-'  w_mon  '-'   p_date0(4)  into w_dt.
    write w_dt.

  • How to convert a optionset into multi selection picklist in crm 2011 using javasacript??

    hi,
    where user want to select not only one but multiple value
    from a pick list. I tried  examples but it shows some errors.
    How  to do it??

    Hey I meet a problème on my development see my result :
    link : https://social.microsoft.com/Forums/getfile/652331
    a multiple select list on my crm 2013 I do this process on this forum :
    link : https://social.microsoft.com/Forums/en-US/2db47a59-165d-40c9-b995-6b3262b949eb/how-to-convert-a-optionset-into-multi-selection-picklist-in-crm-2011-using-javasacript?forum=crmdevelopment
    my development :
    // var_sc_optionset >> Provide schema-name for Option Set field
    // var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
    // OS >> Provide Option Set field object
    // OSV >> Provide text field object which will store the multi selected values for Option Set
    //Method to convert an optionset to multi select Option Set
    function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV)
    if( OS != null && OSV != null )
    OS.style.display = "none";
    Xrm.Page.getControl(var_sc_optionsetvalue).setVisible(false);
    // Create a DIV container
    // var addDiv = document.createElement("<div style='overflow-y:auto; color:#000000; height:160px; border:1px #6699cc solid; background-color:#ffffff;' />");
    var addDiv = document.createElement("div");
    addDiv.style.overflowY = "auto";
    addDiv.style.height = "160px";
    addDiv.style.border = "1px #6699cc solid";
    addDiv.style.background = "#ffffff";
    addDiv.style.color = "#000000";
    OS.parentNode.appendChild(addDiv);
    // Initialise checkbox controls
    for( var i = 1; i < OS.options.length; i++ )
    var pOption = OS.options[i];
    if( !IsChecked( pOption.text , OS, OSV) ){
    // var addInput = document.createElement("<input type='checkbox' style='border:none; width:25px; align:left;' />" );
    var addInput = document.createElement("input" );
    addInput.setAttribute("type","checkbox");
    addInput.setAttribute("style","border:none; width:25px; align:left;");
    else {
    // var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />" );
    var addInput = document.createElement("input" );
    addInput.setAttribute("type","checkbox");
    addInput.setAttribute("checked","checked");
    addInput.setAttribute("style","border:none; width:25px; align:left;");
    // var addLabel = document.createElement( "<label />");
    var addLabel = document.createElement( "label");
    addLabel.innerText = pOption.text;
    // var addBr = document.createElement( "<br />"); //it's a 'br' flag
    var addBr = document.createElement( "br"); //it's a 'br' flag
    OS.nextSibling.appendChild(addInput);
    OS.nextSibling.appendChild(addLabel);
    OS.nextSibling.appendChild(addBr);
    ///////Supported functions
    // Check if it is selected
    function IsChecked( pText , OS, OSV)
    if(OSV.value != "")
    var OSVT = OSV.value.split(";");
    for( var i = 0; i < OSVT.length; i++ )
    if( OSVT[i] == pText )
    return true;
    return false;
    // var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
    // OS >> Provide Option Set field object
    // Save the selected text, this field can also be used in Advanced Find
    function OnSave(OS, var_sc_optionsetvalue)
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = '';
    for( var i = 0; i < getInput.length; i++ )
    if( getInput[i].checked)
    result += getInput[i].nextSibling.innerText + ";";
    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);
    I have to do 2 field one is option list field and the second is textfield, 
    option list field : new_books
    textfiled          : new_picklistvalue
    my js is on onload event see : 
    link : https://social.microsoft.com/Forums/getfile/652333
    thanks you for you'r help 

  • How to convert Property files into Java Objects.. help needed asap....

    Hi..
    I am currently working on Internationalization. I have created property files for the textual content and using PropertyResourceBundles. Now I want to use ListResourceBundles. So what I want to know is..
    How to convert Property files into Java Objects.. I think Orielly(in their book on Internationalization) has given an utitlity for doing this. But I did not get a chance to look into that. If anyone has come across this same issue, can you please help me and send the code sample on how to do this..
    TIA,
    CK

    Hi Mlk...
    Thanks for all your help and suggestions. I am currently working on a Utility Class that has to convert a properties file into an Object[][].
    This will be used in ListResourceBundle.
    wtfamidoing<i>[0] = currentKey ;
    wtfamidoing<i>[1] = currentValue ;I am getting a compilation error at these lines..(Syntax error)
    If you can help me.. I really appreciate that..
    TIA,
    CK

  • How to convert HL7 file into an XML

    Hi All,
    I am new to HL7,can any one tell how to convert HL7 file into an XML.Give sample demo or related links.
    My sample HL7 file is as follows how can I convert.
    FHS|^~\&||Tax ID123^Lab Name123^L|||201110191435||HL7.txt||1234567|123||
    PID|seqno|123||john^chambers^^Dr^Dr|2456 california ave^San jose^CA^85254|19601212|M
    FHS|^~\&||Tax ID123^Lab Name123^L|||File Creaqted Date|File Security|FileName||File HeaderComment||Facility|FileCreatedDateTime|File Security|File Name|File Header Comment|FileControlId|Reference File Control ID|
    PID|seqno|patientId||LastName^FirstName^MiddleName^Title^Degree|Street^City^State^zip|patientDOB|gender
    <Report>
    <FileHeader>
    <FileSendingApplication> </FileSendingApplication>
    <TaxID>Tax ID123</TaxID>
    <LabName>Lab Name123</LabName>
    <FileSendngFacilityType>L</FileSendngFacilityType>
    <FileReceivingApplication></FileReceivingApplication>
    <FileReceivingFacility></FileReceivingFacility>
    <FileCreatedDateTime>201110191435</FileCreatedDateTime>
    <FileSecurity></FileSecurity>
    <FileName>HL7.txt</FileName>
    <FileHeaderComment></FileHeaderComment>
    <FileControlId>1234567</FileControlId>
    <ReferenceFileControlID></ReferenceFileControlID>
    <FileHeader>
    <Patient>
    <seqno> </seqno>
    <patientId>Tax ID123</patientId>
    <LastName>Lab Name123</LastName>
    <FirstName>L</FirstName>
    <MiddleName></MiddleName>
    <Title> </Title>
    <Degree></Degree>
    <Street></Street>
    <City></City>
    <State>HL7.txt</State>
    <Zip></Zip>
    <patientDOB>1234567</patientDOB>
    <gender></gender>
    <Patient>
    </Report>
    Thanks
    Mani

    Hi Prabu,
    With input as in single line I'm able to get the the output but with the multiple lines of input,error was occured.Any suggestions.
    Error while translating. Translation exception. Error occured while translating content from file C:\temp\sampleHL7.txt Please make sure that the file content conforms to the schema. Make necessary changes to the file content or the schema.
    The payload details for this rejected message can be retrieved.          Show payload...
    Thanks
    Mani

  • How to convert nagative integer to positive integer.

    int i= (int)System.currentTimeMillis();
    System.out.println(i);
    The result is nagative
    such as;
    -585450145
    How to convert nagative integer to positive integer.

    Isn't it enough to multiply the integer with -1?!?
    Or did � understand something wrong?
    slaps head
    Yes, but an int is only 32 bits wide; a long is 64
    bits wide.
    The fact that the int is negative isn't "real" - it's
    because they cast it to the wrong type. System time
    in millis is returned as a long, and that's what it
    should be cast to.
    %Doh, I'll get me coat.

  • HT204382 How to convert VOB files into MP4 ? Tks

    Hi, anyone knows how to convert VOB files into MP4 ones ?
    Tks

    http://forums.macrumors.com/showthread.php?t=812985
    The procedure is dated and I will assume that the DVD is not copy-protected since discussion of such things is verboten.

  • How to convert database table into xml file

    Hi.
    How to convert database table into XML file in Oracle HTML DB.
    Please let me know.
    Thanks.

    This not really a specific APEX question... but I search the database forum and found this thread which I think will help
    Exporting Oracle table to XML
    If it does not I suggest looking at the database forum or have a look at this document on using the XML toolkit
    http://download-east.oracle.com/docs/html/B12146_01/c_xml.htm
    Hope this helps
    Chris

  • How to convert select-options into parameters

    hi Abapers,
    i have an urgent requirement, iwant to know how to convert select-options into parameters
    on selection screen,is it possible to do.

    TABLES: spfli.
    SELECTION-SCREEN BEGIN OF BLOCK test.
    SELECT-OPTIONS:
                  s_carrid FOR spfli-carrid NO INTERVALS NO-EXTENSION.
    SELECTION-SCREEN END OF BLOCK test.
    Greetings,
    Blag.

Maybe you are looking for

  • I want to delete a Proof-Setting in Photoshop CS6

    Hello, I want to delete a Proof-Setting in Photoshop CS6. I can only find ways to store these settings, but there is no way to delete them. I can see that the folder (I'm working on a Mac) is named «Proofing» and I know its inside the Color-folder in

  • F110 APP run Error

    Hi Experts, When I try to run F110. Below Error shown. I pasted  Error Job log below: Job started Step 001 started (program SAPF110S, variant &0000000002020, user ID SAPUSER) Log for proposal run for payment on 12.07.2014, identification WIP4 Informa

  • Errors in archive shipping in a standby environment 10.2.0.4

    Hi, I've problem with a standby configuration with real time apply. For month everything works fine, then one day the log shipping from primary to standby fails with error 3135 and sometimes with 1041 and 12571. There's no change in the configuration

  • Minumum Mac Hardware for DVX100B 24p

    I'm looking at purchasing the DVX100B and I have a Mac G4 1 Ghz Dual Processor with 512 RAM and Final Cut Pro HD 4.5. I went to a link on the Panasonic site and it says the DVX100B 24p footage was tested on a Mac G4 1.25 Ghz Dual Processor. I called

  • Cascading a wireless WRT600N to a wired BEFSR81 to the Internet

    Okay, here is an easy one. I am trying to daisy chain a new WRT600N wireless router to an older BEFSR81 8-port router.  Here is the setup up.  Cable modem is wired to the WAN jack on the 8-port.  5 computers (Win98 or Win 2000) wired into the common