Java - Changing the encoding of a string

Soldato
Joined
9 Dec 2004
Posts
5,696
Location
Dorset
Hi all,

I don't program much so I'm not too hot on this stuff.
I need to change the encoding of a variable in my java apps as it isn't what I'm after. I need US-ASCII rather than Unicode. Can anyone suggest a method of how to do change a string into ASCII? I also need to ensure the string is a maximum of 30bytes :(

Thanks in advance for any tips.
 
String unicode = "Unicode: \u30e6\u30eb\u30b3\u30fc\u30c9";
byte[] bytes = unicode.getBytes("US_ASCII");

Be carefull about the escape chars.

Also bare in mind a java unicode char is 2 Bytes (16 Bit) and that a java string object is not just an array of chars, you should be able to work it out from there.
 
Last edited:
Thanks for that, has done the trick.

Another noobie question; What does it do about the spaces? does it ommit them? For the simple reason that I need to pad it out to 30bytes.
 
Following on from all this, I have a byte array of whatever length containing ASCII.

The first 36bytes look like this;

1byte=check
4byte=referencenumber
30byte=username
1byte=numberoflines

So as none of these parts change or reoccur I've pulled them out and converted them to string from ASCII or whatever, as required.

The tricky bit (for me at least) is the next part;

The number of lines refers to how many actions have taken place, in the following sense;

numberoflines byte = 3

so;

One line:

30bytes=action
1byte=number
30bytes=action
1byte=number

Two line:

30bytes=action
1byte=number
30bytes=action
1byte=number

And so on. hopefully that illustrates the case.

Now the problem I'm having is building a for loop to tell itself that by reading the number of lines, it has to;

convert 30bytes into string (print it)
converted 1 into decimal (print it)
convert 30 into string (print it)
convert 1 into decimal (print it)
(one line done)
convert 30bytes into string (print it)
convert 1 into decimal (print it)
convert 30 into string (print it)
convert 1 into decimal (print it)
(second line done).

So far I have this little method;

Code:
            int bytelength = recmessage.length;
            int beginline = 36;
            int m = 65;
            int n = 66;
                while (beginline <= bytelength) {
                        String cut = new String(reply.getData(), beginline, m);
                        out.print("Action:" + cut);
                        int amount = recmessage[n];
                        out.print("£ " + amount + "\n");
                        beginline = beginline + 32;
                        n = n + 31;
                        m = m + 30;
                        out.print("<br>");
                }

Problem is it doesnt work, gives me;

java.lang.StringIndexOutOfBoundsException: String index out of range: 1031

Also, how does the method look? Its been bugging for an hour or so and I've only just put the logic into code as above.

Thanks in advance for any help.
 
Back
Top Bottom