String to byte[] -- I cant get there from here?

R

RVic

I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.

I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.

How do i get there from here? Thanks, Rvince
 
K

Knute Johnson

RVic said:
I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.

I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.

How do i get there from here? Thanks, Rvince

Look at Byte.parseByte().
 
R

RVince

Thanks Knute.

I would have spent all weekend looking for that one! What a large
library! -RVince

RVic said:
I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.
I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.
How do i get there from here? Thanks, Rvince

Look at Byte.parseByte().
 
M

Mayeul

RVince said:
Thanks Knute.

I would have spent all weekend looking for that one! What a large
library! -RVince

However, do note that Byte.parseByte() will only parse signed bytes,
from -0x80 to 0x7f.

When this is not wanted, I usually make a simple method that uses
Integer.parseInt(), makes a few checks and casts to byte.

--
Mayeul
RVic said:
I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.
I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.
How do i get there from here? Thanks, Rvince
Look at Byte.parseByte().
 
R

RVince

Actually, it doesn;t work as I thought. If I say:

Byte.parseByte(hibyteAsString,16);

and hibyteAsString is a String representation of a hex number, it
returns a byte in decimal. I need it in hex -Rvince
 
L

Lew

RVince said:
Actually, it doesn;t work as I thought. If I say:

 Byte.parseByte(hibyteAsString,16);

and hibyteAsString is a String representation of a hex number, it
returns a byte in decimal. I need it in hex

It does not. 'Byte.parseByte( String, int)' returns a byte in byte.

In other words, it returns a numeric quantity, which is what it is in
any base.

Read the Javadocs.
<http://java.sun.com/javase/6/docs/api/java/lang/Byte.html#parseByte
(java.lang.String,%20int)>
 
M

markspace

RVince said:
Actually, it doesn;t work as I thought. If I say:

Byte.parseByte(hibyteAsString,16);

and hibyteAsString is a String representation of a hex number, it
returns a byte in decimal. I need it in hex -Rvince


Primitives (in any language) don't have a base. They're just numbers.
It's how you print them out that matters where base is concerned.
(Well, they're stored as base 2, but conceptually, as far as the
language is concerned, there is no base.)

Look at:
Integer.toHexString( int )
String.format( String, Object... )

Most debuggers too let you chose the base to display numbers in. Maybe
that'll help.

Query: where are you seeing the number in the wrong base? Code please!
 
R

Roedy Green

I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.

I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.

How do i get there from here? Thanks, Rvince

Each char contains two bytes. You can extract them from a char with
ordinary mask/shift operators. From there you can extract the low and
high nibble of each byte. Lookup the corresponding char to display
that nibble in an array. Repeat for each char in the String.

To understand the tools see http://mindprod.com/jgloss/masking.html
http://mindprod.com/jgloss/shift.html


See http://mindprod.com/jgloss/hex.html for the source code.

/**
* convert a String to a hex representation of the String,
* with 4 hex chars per char of the original String, broken into byte
groups.
* e.g. "1abc \uabcd" gives "0031_0061_0062_0063_0020_abcd"
* @param s String to convert to hex equivalent
* @return hex represenation of string, 4 hex digit chars per char.
*/
public static String displayHexString ( String s )
{
StringBuilder sb = new StringBuilder( s.length() * 5 - 1 );
for ( int i=0; i<s.length(); i++ )
{
char c = s.charAt(i);
if ( i != 0 )
{
sb.append( '_' );
}
// encode 16 bits as four nibbles

sb.append( hexChar [ c >>> 12 & 0xf ] );
sb.append( hexChar [ c >>> 8 & 0xf ] );
sb.append( hexChar [ c >>> 4 & 0xf ] );
sb.append( hexChar [ c & 0xf ] );
}
return sb.toString();
}

/**
* table to convert a nibble to a hex char.
*/
static final char[] hexChar = {
'0' , '1' , '2' , '3' ,
'4' , '5' , '6' , '7' ,
'8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f'};
 
R

Roedy Green

I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.

Sorry, I answered the wrong question previously. I tend to guess what
people are really asking rather than what they literally ask, a habit
that comes from teaching newbies.

That problem reduces to how do I convert a string value 0..255
expressed in hex to a byte.

See the converter Amanuensis and ask it how to convert from String to
unsigned byte with radix 16.

See http://mindprod.com/applet/converter.html
 
R

RVince

When I look for String to unsingned byte, I essentially have two
choices, neither of which work.

Take, for instance:

public static void main(String[] args) {
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim());
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
}

This results in :
java.lang.NumberFormatException: For input string: "0F"

Similartly, if I go with:
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim(),16);
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}

It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.

-Rvic
 
A

Arne Vajhøj

RVince said:
When I look for String to unsingned byte, I essentially have two
choices, neither of which work.

Take, for instance:

public static void main(String[] args) {
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim());
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
}

This results in :
java.lang.NumberFormatException: For input string: "0F"

Similartly, if I go with:
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim(),16);
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}

It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.

Parse it as hex *and* print it as hex !

Arne
 
A

Arne Vajhøj

Arne said:
RVince said:
When I look for String to unsingned byte, I essentially have two
choices, neither of which work.

Take, for instance:

public static void main(String[] args) {
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim());
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
}

This results in :
java.lang.NumberFormatException: For input string: "0F"

Similartly, if I go with:
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim(),16);
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}

It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.

Parse it as hex *and* print it as hex !

System.out.println(u);

needs to be modified to:

System.out.println(Integer.toHexString(u));

or something similar.

Arne
 
R

Roedy Green

It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.

It is indeed correct. The value in the unsigned byte primitive does
not have a base. Internally it is stored as binary pulses, so could
say its value was

00001111

you can DISPLAY that same value in several ways:
as decimal 15
as hex F or 0F
or as the corresponding ASCII char

There are always two halves of a problem such as yours:

1. getting an appropriate internal representation

2. displaying that internal value as some sort of String.

To display the unsigned byte, ask the Converter amanuensis to show you
how to convert unsigned byte to String.

It is very common for newbies to think that primitives have a hex or
decimal base or a visual representation. You tend to write the value
for the benefit of other humans as a decimal or hex number, but that
is not what it looks like inside. It is just a string of bits without
and hexness or decimalness.
 
L

Lew

RVince said:
When I look for String to unsingned byte, I essentially have two
choices, neither of which work.

Take, for instance:

public static void main(String[] args) {
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim());
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
}

This results in :
java.lang.NumberFormatException: For input string: "0F"

Similartly, if I go with:
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim(),16);
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}

It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.

Given that the value of the byte was 15, you don't have anything to complain
about when the println() outputs the correct value. Bear in mind that 15
(decimal) and 0F (hex) are the exact same numeric value.

If you wish to display that numeric value of 15 (decimal) as a string with
hexadecimal characters, you have to do a conversion from the numeric value to
a hex string value.

Did you read the Javadocs for 'System.out.println(int)'?
Prints an integer. The string produced by String.valueOf(int)
is translated into bytes according to the platform's default
character encoding, and these bytes are written ...

'String.valueOf(int)' does:
The representation is exactly the one returned by the
Integer.toString method of one argument.

and 'Integer.toString(int)'?
The argument is converted to signed decimal representation and
returned as a string, exactly as if the argument and radix 10
were given as arguments to the toString(int, int) method.

So the conversion by 'println()' uses radix 10, exactly as documented.
However, that chain of research did lead to the 'Integer.toString(int, int)'
method. You could display the value in base 16 by calling:

System.out.println( Integer.toString( u, 16 ));

Always read the Javadocs!
 
R

Roedy Green


Quoting from that entry:

Even though in Java we specify decimal, hex, octal and other radix
representations of int literals, inside the int, there is no radix. It
is just string of 32 binary bits. When you display an int you are in
some way picking a radix and converting it to String. Methods such an
println do this for you, so it creates the illusion you are seeing the
value of the int directly. It does not make sense to talk of the radix
of an int, e.g. is this a hex or decimal int?, only the radix of some
String representation of it.
 
R

RVince

Thanks guys. I have to read the input from a socket connection. The
first byte represents the length of the message in hex, so it can be
something like, 6B. I can read the byte and convert it to the length.
However, when I send the response, I need to comport to this standard
and send my length (which I have as an int and as a two-character long
String representing what the byte in hex should look like) but I need
to send it as a byte in hex. So, for example, if the length is merely
15 bytes, I need to send a 0F as a byte. I THINK, based on what you;ve
said here, that this would be the equivalent of (byte)15.
 
L

Lew

RVince said:
I have to read the input from a socket connection. The
first byte represents the length of the message in hex, so it can be
something like, 6B. I can read the byte and convert it to the length.

The characters "0F" ("zero eff") or "6B" ("six bee") will not fit in a single
byte, so what you wrote here doesn't make sense. What does fit in a byte is
the numeric value 0x0F, which is EXACTLY THE SAME as 15.
However, when I send the response, I need to comport to this standard
and send my length (which I have as an int and as a two-character long
String representing what the byte in hex should look like) but I need
to send it as a byte in hex. So, for example, if the length is merely
15 bytes, I need to send a 0F as a byte. I THINK, based on what you;ve
said here, that this would be the equivalent of (byte)15.

A byte, as several people keep telling you, just holds a numeric quantity. 0F
hex is THE SAME NUMBER as 15 decimal.

So if you have the following code snippet:

byte zeroEff = (byte) 0x0F;
byte fifteen = (byte) 15;
boolean theSame = (zeroEff == fifteen);

the value of 'theSame' after the assignment will be 'true'.

Ergo, one way to send a byte value 0x0F to an output stream 'out' would be

out.write( 15 );
 
R

Roedy Green

mple, if the length is merely
15 bytes, I need to send a 0F as a byte. I THINK, based on what you;ve
said here, that this would be the equivalent of (byte)15.

yes.

You specify it as (byte)15 or (byte)0xf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top