| Author |
BCD convert to String ascii and back
|
Axel Richardson
Greenhorn
Joined: Jun 28, 2012
Posts: 3
|
|
Hello All,
I am stuck at solving a problem I have been having.
Maybe someone could help me. Any help is appreciated.
The problem is that I need to convert 4 decimal numbers into ascii chars. I am using BCD converter I found on:
BCD converter
Example code
When I try to system out the res, the result is 'w?' (?= unrecognisable ascii char). But thats not actually a problem since I dont actually need to 'read' out those characters.
The problem appears when I try to decode res. The first part will be 77 but the last 2 will be something like =' . So it decodes the result falsely. (it decodes values 7 or under that easily e.g. '6545')
What I am actually trying to do is to encode the last 4 numbers and add some random value (e.g. hash) to it and save it to SQL.
Correct me if I'm wrong, but the problem appears when I use String(byte) and then it loses some of its value.
Is there any way to get this solution working? Like alternative to String perhaps?
So if you have any ideas, or wish to point out an error or anything else, please go ahead.
Thank you in advance.
Update: for value 7788, the return bytes are 119 and -120. It seems when I convert it to string it keeps the negative and tries to ascii a negative char. and thats causing the problems (when i directly decode bytes(BCD.decode(b)), it seems to count for the negative, but when i BCD.decode(res.getBytes()) then it doesnt decode properly. Is there any solution to that or ideas?
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
Welcome to the Ranch.
First of all, why exactly do you need to encode the number in BCD format?
You can't store arbitrary binary data in a String, so doing something like String res = new String(b); is not going to work. If you do this, then class String will interpret the bytes as characters using your system's default character encoding and you'll get strange results like 'w?' or other unrecognizable characters. What exactly would you expect to see in the string?
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Axel Richardson
Greenhorn
Joined: Jun 28, 2012
Posts: 3
|
|
Thanks for the reply. this was mostly used to store it in db (for easy protection) and then back..
I managed to solve it by changing the bytes to chars to prevent it to use encoding (does not encode chars on String)
|
 |
 |
|
|
subject: BCD convert to String ascii and back
|
|
|