🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #7999

Re: Byte Array Conversion to Integer

#7999
From: Tim Dietz
Date: Tue, 08 May 2001 15:01
39 lines
2069 bytes
Here's a static method that we use:

 public static int ByteArrToInt(byte[] bA)
   throws ArrayIndexOutOfBoundsException
 {
  if (bA.length != 4)
   throw new ArrayIndexOutOfBoundsException("Array must be 4 bytes");

  int result = ((int)bA[0] << 24) & 0xff000000;
  result |= ((int)bA[1] << 16) & 0x00ff0000;
  result |= ((int)bA[2] << 8) & 0x0000ff00;
  result |= ((int)bA[3]) & 0x000000ff;

  return result;
 }

You may need to adjust this depending upon the endian-ness of your system.


Tim

"Tom Heagy" <tom.heagy@sciatl.com> wrote in message
news:3af6e910$1_2@dnews...
> Question:  How do I convert a byte array to an int or Integer?
>
> Problem:  I'm receiving a TCP InputStream from a C application.  The
stream
> consists of a byte array that was built by the C application.  Part of the
> byte array contains a number (converted to it's 4 byte format).  How do I
> take these 4 bytes and convert them into a number I can use in my Java
> application?  The String class provides a conversion constructor method
for
> use with byte arrays but I can't find anything similar for numbers.
>
> Any suggestions would be greatly appreciated.
>
> -Tom
>
>
Technical Details
Message-ID: <3af80a58$1_2@dnews>
Path: arc1-ca.pugleaf.net!newsfeed.google.com!sn-xit-03!sn-xit-04!supernews.com!newsfeed.ision.net!ision!fr.usenet-edu.net!usenet-edu.net!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!dnews
References: <3af6e910$1_2@dnews>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,840940854720c53
X-Google-Attributes: gidf74b3,public
X-Google-ArrivalTime: 2001-05-08 08:44:06 PST
From: "Tim Dietz" <tdietz@telena.com>
Newsgroups: borland.public.jbuilder.java.language
References: <3af6e910$1_2@dnews>
Subject: Re: Byte Array Conversion to Integer
Date: Tue, 8 May 2001 08:01:03 -0700
Lines: 41
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.50.4133.2400
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4133.2400
NNTP-Posting-Host: 207.110.36.206
Message-ID: <3af80a58$1_2@dnews>
X-Trace: dnews 989334104 207.110.36.206 (8 May 2001 08:01:44 -0700)
Path: arc1-ca.pugleaf.net!newsfeed.google.com!sn-xit-03!sn-xit-04!supernews.com!newsfeed.ision.net!ision!fr.usenet-edu.net!usenet-edu.net!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!dnews