1

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?

Richard Povinelli
  • 1,419
  • 1
  • 14
  • 28
Mohamad Ibrahim
  • 5,085
  • 9
  • 31
  • 45

4 Answers4

3

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • It seems the OP just wants to transform ASCII data to binary data, which works perfectly fine in Java as well.. – Voo Nov 26 '11 at 18:34
2

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.

Pavan
  • 1,245
  • 7
  • 10
  • True, but I need a way to store those numbers as binary numbers and not characters. and then convert them to characters when running the program.. any ideas?! – Mohamad Ibrahim Nov 26 '11 at 17:27
0

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

Community
  • 1
  • 1
gigadot
  • 8,879
  • 7
  • 35
  • 51
0

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.

Richard Povinelli
  • 1,419
  • 1
  • 14
  • 28