• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 1093
29
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: 15510
363
  • 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.
 
No prison can hold Chairface Chippendale. And on a totally different topic ... my stuff:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic