Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert a long into an 4-byte sequence

Status
Not open for further replies.

balajee

Programmer
Jun 29, 2000
134
NZ
Hi

I am trying to calculate the checksum using CRC32 and storing the long value returned by this class in a byte array. I have to store this long value in 4 bytes.

how do I do this.

Thanks
 
You can code a loop where you divide the "long" by 256, take the rest, then you have the "Least Significant Byte" ...
(depending on whether you want little-endian or big-endian you can loop forwards or backwards)
Code:
public class Test3 {

  public Test3() {
  }

  private void doIt() {
      byte[] b = new byte[4];
      long l = (8* 256 * 256 * 256 + 3 * 256 *256 + 5 * 256 + 7);
      long l2 = l;
      System.out.println("long = " + l);
      for (int i=0; i<4; i++) {
        b[i] = (byte)(l % 256) ;
        l = l / 256;
        System.out.println(&quot;  byte[&quot; + i + &quot;] = &quot; + b[i]);
      }
      l = l2;
      for (int i=3; i>=0; i--) {
        b[i] = (byte)(l % 256) ;
        l = l / 256;
        System.out.println(&quot;  byte[&quot; + i + &quot;] = &quot; + b[i]);
      }

  }

  public static void main(String[] args) {
    Test3 example = new Test3();
    example.doIt();
  }

}
 
>> I have to store this long value in 4 bytes.
Code:
static byte[] getLongBytes(long l){
    java.math.BigInteger bi = new java.math.BigInteger( Long.toString(l));
    return bi.toByteArray();
}

-pete
 
Thanks guys.
This for palbano

How can I undo this (convert the value from byte array to long) and see if I get the same long value.
 
Dude, your profile says you have been a Tek-Tips member for 3 years. As a programmer don't you know how to research documentation? It takes you longer to post that question and wait for a response than it does to look up the BigInteger documentation and see the answer for yourself!

[red]Think &quot;Developer&quot; and GET SERIOUS![/red]

-pete
 
I am just a week old in Java. I have to complete this tutorial program by Tuesday. I am finding it difficult to understand Java.
Anyway if you do not want to answer its OK.

Thanks,
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top