简体   繁体   中英

how to convert a large integer to Ascii character string in java?

I have seen many methods to convert string to ascii. For example

"Nkn" = 78 + 107 + 110 = 78107110

But is there a way to easily convert back 78107110 to "Nkn" (Since ascii codes of each character can vary in length from 1 to 3)

But is there a way to easily convert back 78107110 to "Nkn" (Since ascii codes of each character can vary in length from 1 to 3)

If the words does not need to have a meaning, NO .

You can implement a function that tries to do it, in this single case it should work without problem:

78107110 = "NkN"
78 = "N" because 781 is not valid ascii character
107 = "k" because 10 is LF special character
110 = "n" because 11 is VT special character

But there are a lot of cases that is not possible to know the result, and if the Strings are not words you can compare against (for example) a dictionary, you won't know it the result is the right one.

WORKAROUND:

But this is programming and we always have a plan b... If what you want to do is a complete function to convert/revert, for example you can pad the characters you can after get the reverse:

"Nkn" = 078 + 107 + 110 = 078107110

revert:

078107110 = 078 + 107 + 110 = "Nkn"

How to pad a number to be 3 characters and complete it with 0 if less size?

 String numberPadded = String.format("%03d", yournumber);

Simple answer: no. There is no definite way of splitting this string into byte-long-values. Any format must provide a way to determine how the text can be interpreted. This can be either done by using fixed offsets, or using markers, etc..

In your case there would be several simple workarounds:

  • Use a fixed length for the values and pad from the beginning with 0s:
    For example: 3270128 with 32,70,128 becomes 032070128, and can be split in a distinct way.
  • Use hex instead of decimal representation. This way each byte/char is represented by 2 digits and can be restored in a distinct way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM