[java] Best way String->Bytes->Int?

Started by
7 comments, last by Spyder 22 years, 8 months ago
I have a string composed of 4 bytes that add up to an integer sum. What is the best way to figure this out? At the moment I'm doing this: String s = "aBcL"; byte b []= s.getBytes(); int i= b[0]+b[1]+b[2]+b[3]; There must be a better way? Edited by - Spyder on July 26, 2001 8:01:15 PM
Advertisement
Why are you doing this? It doesn''t seem like a good way to do much of anything in particular. What is your ultimate goal here?
My server is receiving this as part of a protocol. 4 bytes are used
to determine the message size. All i want to know is if there is a
cleaner way to extract and add the bytes from the string.
I think you are doing it OK, but is it 4 bytes that add up to the sum, or a 4 byte sum...

size = b[0] | ( b[1] << 8 ) | ( b[2] << 16 ) | ( b[3] << 24 );

Your way will produce a byte value between -128 and 128.

Unfortunatly there are very few conversion rouitines in java that can do stuff like this. They are correcting that in 1.4, but I doubt it would be worth it.

You could try:

String s = "aBcL";int i = unsigned(s.c_str[0]) + unsigned(s.c_str[1]) + unsigned(s.c_str[2]) + unsigned(s.c_str[3]); 


To remove a step.

But I think your logic is flawed. If you are recieving 4 bytes to indicate the message size, it is probably a 32 bit integer value, so you maybe want to get it like so:

unsigned int i = (b[0]<<24)|(b[1]<<16)|(b[2]<<8)|(b[3]);  


Or maybe just:

unsigned int i = *((unsigned int*)b);  



Did someone forget that this is a *** Java *** forum?
Of course, the AC who forgot this is a java forum has a good point... Why are you representing this as a string? If you''re using text based IO, represent the size as a string containing only digits in the ''0''-''9'' range, and parse it with Integer.parseInt(). In order to protect the server (or at least the input thread) from crashing, you''d have to catch NumberFormatException, but that''s not a big deal.

If you''re using binary IO, do it right and use DataInputStream and DataOutputStream.

The problem here comes from trying to mix binary and text IO. Use one or the other, and you won''t have this problem.
It seems Anonymous Poster has reversed the sequence in comparison to snowmoons:

size = b[0] | ( b[1] << 8 ) | ( b[2] << 16 ) | ( b[3] << 24 );


I don''t really understand whats going on above, where can I read up on it on the web? And if this is to decode the size how do i code the size myself?
Spyder,

The diffrence really just depends on who is sending the data. Diffrent systems send data either as Big endian or Little endian. Those are both topics that can be researched on the web. You will find that BOTH are correct depending on why type of system you are interacting with.

This topic is closed to new replies.

Advertisement