• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

turning a string into a byte array

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I found this post here showing multiple solutions on this, and an answer is selected, but I just can't get it to work on my part.

Expected output:

input: String hexString = "1234";
output: byte[] {0x12,0x34}

here is my code:



My output:

instead of "0x12" I get "18". Which could be the byte presentation of 12, as this answer was accepted I guessed that it should also work as the OP stated. Can anyone tell me what I'm doing wrong here?

I found an alternative solution:

 
Rancher
Posts: 1059
27
Netbeans IDE Oracle MySQL Database Tomcat Server C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not sure what you are asking: if I understand you get the string split and you get 18 in one of the bytes -- 18 is 0x12: 16x1+2 -- so if you are asking is why you are getting 18 instead of a hex number out, you need to format the number as a hex when you print it.
 
Saloon Keeper
Posts: 14498
325
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're interpreting the string "12" as hexadecimal. Note that the base of a number is not a property of the number, but of the string representation. 12 base 16 is equal to 18 base 10. Arrays.toString() uses base 10 to display numbers.

If you want to display the bytes as hexadecimal values, you'll have to convert them that way first, as Les already said.
 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic