Reputation: 5555
I have numbers written as ASCII codes each of 2 bytes which wastes a lot of the space. I want to convert those number to their corresponding ASCII code to save the space.
Any idea?
Upvotes: 1
Views: 1808
Reputation: 1439
Convert the two digit ASCII string to a byte. When you need the ASCII back just convert it to a string. The following code shows how to do this for "95".
public class Main { public static void main(String[] args) { byte b = Byte.parseByte("95"); String bString = "" + b; } }
If you need to change the way they are stored in a file, just read the two digit text numbers in as strings and write them out to another file as bytes.
Upvotes: 0
Reputation: 8969
Do you want to convert the Hex number to bytes? If so, this is your answer:
Convert a string representation of a hex dump to a byte array using Java?
If you want to convert number to byte -> http://snippets.dzone.com/posts/show/93
Upvotes: 0
Reputation: 308763
If you mean characters, Java uses two bytes per character as part of its Unicode support. If you give ASCII values, Java will make the upper byte zero. You won't save a thing.
If you mean floats or doubles or ints, the bytes per value are fixed there as well.
You're barking up the wrong tree. I don't think this will save you anything no matter what you do.
You're better off writing C or C++ if you need that kind of optimization, not Java.
My first thought is that this is an imagined optimization that isn't supported by data. The only application that would justify something like this would be scientific computing on a large scale. Even that wouldn't justify it, because you'll need more precision than a byte per value.
Upvotes: 3
Reputation: 1247
You can use the parse methods on the default types' class. For example, if these numbers are integers and are stored as string "34", you can use Integer.parseInt("34") which returns you a single int whose value is 34. Similarly for Double, Float and Long.
Upvotes: 2