Convert a byte/Byte - HEX STRING ?

Hi ,
My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
please help me.

Integer.toHexString(byteValue);
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

Similar Messages

  • How could I choose some bytes from HEX string and then convert it to a decimal value?

    Hi I am working with an OMRON E5EN temperature controller using VISA serial to get data, I send the Read from Variable Area command and get this string  in hexa 0230 3130 3030 3030 3130 3130 3030 3030 3030 3030 3041 3203 71 or .01000001010000000000A2.q in ASCII this string means:
    02 STX
    3031 3030 Node and subadress
    3030 End Code Normal Completion
    3031 3031 Command Read from Variable Area
    3030 3030 respt code Normal completion
    3030 3030 3030 4132 Hexadecimal A2 = 162  (this is the temperature data that I want to show in decimal)
    03 ETX
    71 Block Check Character
    I want to choose the eight bytes for the temperature data and convert it to a decimal number. I have seen the examples to convert a Hexa string to decimal but I do not know how to choose the specifics bytes that I need.
    I have look for a driver but i didn´t find any. I am a beginner so please include especific topics for me to study in your answer.
    Thanks
    Carlos Fuentes Silva Queretaro Mexico 

    If the response always has the temperature starting with byte 15 and is always 8 bytes in length, you can use the String Subset function to get those bytes out of the string.  Then use Hex String to Number to convert to a decimal number.
    Well someone already beat me to the solution:
    Message Edited by tbob on 01-04-2008 04:42 PM
    - tbob
    Inventor of the WORM Global
    Attachments:
    HexStr2Decimal.png ‏7 KB

  • Bytes and hex woes

    I am sending data to the serial port and it must be in hexadecimal format. I'm using a method that sends a byte array to the serial port.
    putData(byte[] barray);I've created a byte[] array and initialized it to the following values.
    byte byteBuf[] = {  0x10, 0x40, 0x80 };
    How can I be sure that the 0x prefix is being sent. Namely, how can I send the hex value in the byte array. Also, I get a
    possible loss of precision error
    found : int
    required: byte
    byte byteBuf[] = {  0x10, 0x40, 0x80 };
                                ^     ^
    Any ideas would be greatly appreciated, Cheers.

    Because of the way two's complement binary and signed bytes work. Your 0x80 byte is expressed in binary as 10000000. This is the equivalent of -128 in decimal by virtue of Java's bytes always being signed (the leftmost bit indicates whether the byte is positive or negative). When you run the conversion to an integer, it has the binary look of:
    11111111 11111111 11111111 10000000
    This is still -128 in decimal. When you then convert this to a hex String, it looks at each "octet", so the integer then becomes:
    11111111 = FF
    11111111 = FF
    11111111 = FF
    10000000 = 80
    Or, FFFFFF80.
    Make sense?

  • Which bytes should be edited in a WMF hex string stored in an RTF file in order to change image dimensions?

    I  would like to save the WMF file with proper dimensions as they are in the editor (my saved WMFs have the dimensions of my screen resolution).  They come from a RichEdit.
    Thanks.
    Edit:
    My goal is to convert the images that appear on a RichEdit to another format.
    Here is the fragment of the RTF:
    {\pict\wmetafile8\picw7407\pich9259\picwgoal4199\pichgoal5249 
    010009000003703e020000005a3e02000000050000000b0200000000050000000c022b24ef1c5a
    ffffffffffffff030000000000
    }\cf2\lang1033\b\f1\fs23\par
    For each 2 chars in this string I converted it to hex and saved it through a memory stream. Then I opened it in Paint or GIMP and there is the image.  I even can convert it to a PNG file through ImageMagick tool. But the dimensions are wrong. How to fix
    this?
    I am using Lazarus.
    I could guess that the header is not OK, but how they can be opened by Paint and converted? So I guess the dimensions info is wrong in the header. In GIMP even the dimensions are right, here a link to the GIMP's dialogbox confirmation with the dimensions
    it has encountered in the file (  http://s13.postimg.org/s536tgo9z/Metafile_in_GIMP.png  ).
    So the info is there, but is wrong. When I open the images in Paint, they are wrong. Microsoft Office Picture Manager can also open them correctly, but could not convert them so. I need to do it programmatically. TMetafile Delphi class could not open these
    files as well in order to be converted. So I could only edit the bytes.
    My RichEdit WMF data can not be accepted by ComputeAldusChecksum routine nor get a handle from SetWinMetaFileBits API call, which would convert it to an EMF format.
    procedure TMetafile.ReadWMFStream(Stream: TStream; Length: Longint);
    var
    WMF: TMetafileHeader;
    BitMem: Pointer;
    MFP: TMetaFilePict;
    begin
    NewImage;
    Stream.Read(WMF, SizeOf(WMF));
    if (WMF.Key <> WMFKEY) or (ComputeAldusChecksum(WMF) <> WMF.CheckSum) then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<<< exception here
    Dec(Length, SizeOf(WMF));
    GetMem(Bitmem, Length);
    with FImage do
    try
    Stream.Read(BitMem^, Length);
    FImage.FInch := WMF.Inch;
    if WMF.Inch = 0 then
    WMF.Inch := 96;
    FWidth := MulDiv(WMF.Box.Right - WMF.Box.Left,25400,WMF.Inch);
    FHeight := MulDiv(WMF.Box.Bottom - WMF.Box.Top,25400,WMF.Inch);
    with MFP do
    begin
    MM := MM_ANISOTROPIC;
    xExt := 0;
    yExt := 0;
    hmf := 0;
    end;
    FHandle := SetWinMetaFileBits(Length, BitMem, 0, MFP); 
    if FHandle = 0 then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<< exception here
    Enhanced := False;
    finally
    Freemem(BitMem, Length);
    end;
    end;

    Hi Antônio G,
    Based on your description, I’m afraid that it is not the correct forum for this issue, since this forum is to discuss:
    Visual Studio WPF/SL Designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System, and Visual Studio Editor.
    To make this issue clearly, would you mind letting us know more information about this issue? Which language are you using? Which kind of app are you developing?
    Reference:
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/a9e1857d-dd5b-443b-8633-397aea6e7b8c/help-on-properly-handling-wmf-mmanisotropic-image-in-rtf-file-when-extracted?forum=csharpgeneral
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/5b99d331-ef56-4d60-bf12-3e3b70783376/how-to-convert-a-hex-string-save-in-a-rtf-file-into-an-image-jpg-or-bmp?forum=csharpgeneral#a9219408-f73b-4e98-a9d8-7a1e0f20cdd9
    Maybe you could select the language development forum for this kind of issue. If not, please let me know more information about it, I will help you find a more appropriate forum.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Conversion from hex string to bytes withh out ascii

    how to convert hex string to byte numbers without ascii codes,then all the converted bytes should come into a packets

    rajkumar5 wrote:
    how to convert hex string to byte numbers without ascii codes,then all the converted bytes should come into a packets
    What people consider ASCII and Hex with strings varies so much, you pretty much need to supply an example.  The best way is to create a VI with default data in the string control and indicator (to show what you want out).

  • Converting ASCII text (byte array ending in null) to a String

    Hi all,
    I am trying to convert a null terminated ascii string stored in a byte array to a java String. When I pass the byte array to the String constructor it
    does not detect/interpret the null as a terminator for the ascii string. Is this something I have to manually program in? ie Check for where the null is and then
    pass that subarray of everything before the null to the String constructor?
    example of problem
    //               A   B  C   D   null   F   (note F is junk in the array, and should be ignored since it is after null)
    byte[] asciiArray = { 65, 66, 67, 68, 0,  70 };
    System.out.println(new String(asciiArray, "UTF-8"));
    //this prints ABCD"sqare icon"F

    Why do you expect the null character to terminate the string? If you come from a C or C++ background, you need to understand that java.lang.String is not just a mere character array. It's a full-fledged Java object that knows its length without having any need for null terminator. So Ascii 0 is just another character for String object. To achieve what you want to do, you have to manually loop through the byte array and stop when you encounter a null character.

  • Converting Image to Byte Array and then to String

    Hi All...
    Can anyone please help me. I have got a problem while converting a Byte array of BufferedImage to String.
    This is my code, First i convert a BufferedImage to a byte array using ImageIO.wirte
    public String dirName="C:\\image";
    ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
    BufferedImage img=ImageIO.read(new File(dirName,"red.jpg"));
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] resultimage=baos.toByteArray();
    baos.close();
    Then i tried to convert this byte array to a string
    String str=new String(resultimage);
    byte[] b=str.getBytes();
    This much worked fine. But when i reversed this process to re-create the image from that string. i found the image distroted.
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(b));
    ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    I got this snap.jpg as distroted.
    Please help me i have to convert the image to a string and again i have to re-create the image from that string.

    To conver the bytearray to string use base64.encoding
    String base64String= Base64.encode(baos.toByteArray());
    To convert back use Base64.decode;
    byte[] bytearray = Base64.decode(base64String);
    BufferedImage imag=ImageIO.read(bytearray);

  • 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 convert hex string to time stamp?

    Hello everyone..
    I am currently working on a project in which I have to read the data from a unit and display that data using LabVIEW. I am using serial communication for reading the data. The read data is in hex format. 
    Now, I want to convert this hex string to a time stamp value. I am reading total 16 bytes. How to convert this hex data to a time stamp value. I have developed a VI. But I want to know that the displayed time stamp is correct or not? Or suggest me some other solution. 
    I am using LabVIEW 2011.
    Thanks & Regards,
    Manisha
    Attachments:
    Test.vi ‏7 KB

    Hi mancan,
                      As Iam using LV2009 Iam unable to open your example.Anyway for converting hex to time stamp
    Thanks as kudos only

  • Help needed in understanding conversion alghorithm from byte to hex

    Hi, I'm studying the following code:
    public static char[] byteToHex(byte[] data) {
      char[] retValue = new char[data.length * 2];
      int value = 0;
      int highIndex = 0;
      int lowIndex = 0;
      for (int i = 0; i < retValue.length; i++) {
        value = (data[i] + 256) % 256;
        highIndex = value >> 4;
        lowIndex = value & 0x0f;
        retValue[i * 2 + 0] = hexTable[highIndex];
        retValue[i * 2 + 1] = hexTable[lowIndex];
      return retValue;
    }There are few things (the most important) which I don't understand about the above code.
    I understood that what's returned has got double size related to what's passed in because a char takes 16 bits while a byte takes 8.
    1) I don't understand why each byte must be first added 256 and then % with 256 (returning the same value - Is this to eliminate negative values?)
    2) I do understand that each byte is transformed in two hexadecimal values: one is the highIndex (first 8 bits) and the second is the lowerIndex (last 8 bits) and that each value is tranformed in its hexadecimal value from the array of hex values.
    3) What I don't really understand is why the highIndex is calculated as: value >> 4
    and the lowest index is calculated as value 0x0f (is this last also to eliminate negative values?)
    If someone could clarify this for me, I'd be very grateful.
    Thanks.
    Marco

    So, does this mean that we add 256 to eliminate the sign?No. You need the whole line to convert a signed byte into an int between 0 and 255.
    A simpler way to do this would be
    value = data[i] & 0xFF;
    This moves down the higher bits so that it turnsinto lower bits. i.e. we need it to >be between 0 and
    15.
    Is this shifted of 4 because Math.pow(2, 4) = 16.0?Doing in this case, x >>4 is the same as x / 16
    This leaves only the lowest 4 bits.Is the following what happens?There are no char values produced. Using 0000 as an example is not a good idea as you can change it in many ways and it is still 0000
    >
    Received as initial value:
    byte: 0000 0000
    What we need to obtain:
    char: 0000 0000 0000 0000
    The first 4 bits of the above byte are shifted of 4
    positions to find the hexadecimal equivalent (if from
    2 I want to get to 16 I have to do the opposite of
    powering a number by 4); The last four bits of the
    byte are extracted because of the '&' operator with
    0x0f (which in binary is 1111 - Therefore all the '1'
    are kept)?Yes.

  • Image Byte Array - Hex?

    Hi all,
    I'm trying to read in an image and get an int / hex array out of it. Basically, I want to get an array that would look like what you see if you open an image in a hex editor. I have no problems getting a byte array using..
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write( bufferedImage, "jpg", stream );
    bytes = stream.toByteArray();
    But, it's weird, it's not really what I want. The result is not the same as what I see if I drop the same image into a hex editor and look at the bytes. Not sure if I need to convert the bytes to hex or what. Any help would be much appreciated.

    hmm.. can you explain a bit?.. let's say I do...
    BufferedImage srcImage = ImageIO.read( new File( pathIn ));
    ByteArrayOutputStream streamIn = new ByteArrayOutputStream();
    ImageIO.write( srcImage , "jpg", streamIn );
    byte[] bytes = stream.toByteArray();
    ByteArrayInputStream streamOut = new ByteArrayInputStream( bytes );
    BufferedImage writeImage = ImageIO.read( streamOut );
    ImageIO.write( writeImage, "jpg", new File( pathOut ));Looks a little odd out of context, I know. But, basically, the resulting image is different than the original image. I assume, maybe, there is some sort of compression going on. But i don't really know. Should I be decoding / encoding in specific formats to get the resulting image to be /exactly/ the same as the source?
    thanks

  • Memory leak in String(byte[] bytes, int offset, int length)

    Has anyone run into memory leak problem using this String(byte[] bytes, int offset, int length) class? I am using it to convert byte array to string, and I am showing memory leak using this class. Any idea what is going on?

    Hi,
    If you post in Native methods forum I assume you are using this constructor in the native side.
    Be aware that getting char * from jstring eats memory that you must free before returning from native with env->ReleaseStringUTFChars().
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • How to get the length in bytes of a string

    My string has both latin (1 byte) and chinese (2 bytes).
    My program is in unicode system.
    How to measure the length in bytes of the string?
    the xlen function does not work.

    Hello,
    parameters : p_str type string.
    data : len type i.
    len = strlen( p_str ).
    write : / len.
    With Regards,
    BVS
    Hi BSV, your code return the number of characters not bytes.
    Remember chinese character in US are encoded with 2 bytes.
    And my string contain both latin and chinese characters.
    thanks

  • How do I convert a double-byte encoded file to single-byte ASCII?

    Hello,
    I am working with XML files (apparently coded in UTF-8) which encoded in double-byte characters.
    The problem is the characters for end of line: 00 0D 00 0A
    This double byte end of line is causing a problem with a legacy conversion tool (which deals with 0D 0A). The file itself contains no
    accented/international characters, so in principle converting to single-byte should not cause any problems.
    I have tried to convert this file with tools like native2ascii and the conversion tools that are part of Notepad++ but without
    any luck - the "00 0D 00 0A" are still present in the output
    Can anyone point me to a tool or some code that can convet this file into single-byte?
    Thank you.

    Amiens wrote:
    native2ascii.exe -encoding UTF-16 -reverse INPUT.xml OUTPUT.xml
    gives 00 00 0 0D 00 00 00 0A
    so clearly that is not the required output.What you've got there is UTF-16 encoded text that's been converted to UTF-16. Get rid of the "-reverse" option and you should see the result you expect.

Maybe you are looking for