Article View: borland.public.jbuilder.java.language
Article #16196Re: Byte swapping
From: Chris Hill
Date: Tue, 16 Mar 1999 00:00
Date: Tue, 16 Mar 1999 00:00
73 lines
2327 bytes
2327 bytes
You need to do it differently in Java.
private short swap2(short s)
{
short tmp1, tmp2;
tmp1 = (s & 0xFF) << 8;
tmp2 = (s >> 8) & 0xFF;
return (tmp1 | tmp2);
}
and call it with
sval = swap2(sval);
I think that will work, and a similar procedure would work for 4 byte
numbers (int in Java). Depending on what you are doing be careful
with the sign (+/-).
To convert between floats and ints see Float.floatToIntBits and
Float.intBitsToFloat (the JDK documentation explains the format of the
int).
On Tue, 16 Mar 1999 09:45:23 -0700, Doug Bath <dbath@agt.net> wrote:
>Greetings
>
>I am trying to convert an old C++ app to java and I have hit a snag. I
>am writing a class to read seismic data in SEGY format which consists of
>short integers, long integers, and floats in IBM and IEEE format. These
>values can be in 'big endian' or 'little endian' byte order.
>In my C++ app I wrote simple byte swap routines for 2 byte or 4 byte
>values that looke like
>
>void TSegyFile::swap2(unsigned char *str)
>/* byte swap 16 bit integers */
>{
> unsigned char tmp;
>
> tmp=str[0];
> str[0]=str[1];
> str[1]=tmp; // wrote a similar function for 4 byte values
>}
>
>To call the function I cast the short integer to an unsigned char as
>
>swap2((unsigned char*)&sval);
>
>When I try to do something similar in java
>private void swap2(byte[] s)
> {
> byte tmp;
>
> tmp=s[0];
> s[0]=s[1];
> s[1]=tmp;
> }
>
>and call it with
>swap2((byte[]) sval);
>
>I get a message telling me I can't make such a cast.
>
>I haven't even got to the point where I have to cast a float to a long
>int to do the IBM to IEEE conversion but I am already dreading it.
>
>Any insights would be most appreciated.
>
>
>Doug Bath
>
Chris Hill
Chris244@aol.com
Technical Details
Message-ID:
<36eeb7cc.66297370@forums.borland.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<36EE8AA3.3212A98D@agt.net>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,a228e969071f0feb X-Google-Attributes: gidf74b3,public From: Chris244@aol.com (Chris Hill) Subject: Re: Byte swapping Date: 1999/03/16 Message-ID: <36eeb7cc.66297370@forums.borland.com> X-Deja-AN: 455747123 References: <36EE8AA3.3212A98D@agt.net> Organization: Another Netscape Collabra Server User Newsgroups: borland.public.jbuilder.java.language