Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3333592
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T23:48:50+00:00 2026-05-17T23:48:50+00:00

I’m trying to figure out how to calculate the Internet Checksum in Java and

  • 0

I’m trying to figure out how to calculate the Internet Checksum in Java and its causing me no end of pain. (I’m horrible at bit manipulation.) I found a version in C# Calculate an Internet (aka IP, aka RFC791) checksum in C#. However my attempt at converting it to Java does not see to produce the correct results. Can anyone see what I’m doing wrong? I suspect a data type issue.

public long getValue() {
    byte[] buf = { (byte) 0xed, 0x2A, 0x44, 0x10, 0x03, 0x30};
    int length = buf.length;
    int i = 0;

    long sum = 0;
    long data = 0;
    while (length > 1) {
        data = 0;
        data = (((buf[i]) << 8) | ((buf[i + 1]) & 0xFF));

        sum += data;
        if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
        }

        i += 2;
        length -= 2;
    }

    if (length > 0) {
        sum += (buf[i] << 8);
        // sum += buffer[i];
        if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
        }
    }
    sum = ~sum;
    sum = sum & 0xFFFF;
    return sum;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T23:48:50+00:00Added an answer on May 17, 2026 at 11:48 pm

    Edited to apply comments from @Andy, @EJP, @RD et al and adding extra test cases just to be sure.

    I’ve used a combination of @Andys answer (correctly identifying the location of the problem) and updated the code to include the unit tests provided in the linked answer along with a verified message checksum additional test case.

    First the implementation

    package org.example.checksum;
    
    public class InternetChecksum {
    
      /**
       * Calculate the Internet Checksum of a buffer (RFC 1071 - http://www.faqs.org/rfcs/rfc1071.html)
       * Algorithm is
       * 1) apply a 16-bit 1's complement sum over all octets (adjacent 8-bit pairs [A,B], final odd length is [A,0])
       * 2) apply 1's complement to this final sum
       *
       * Notes:
       * 1's complement is bitwise NOT of positive value.
       * Ensure that any carry bits are added back to avoid off-by-one errors
       *
       *
       * @param buf The message
       * @return The checksum
       */
      public long calculateChecksum(byte[] buf) {
        int length = buf.length;
        int i = 0;
    
        long sum = 0;
        long data;
    
        // Handle all pairs
        while (length > 1) {
          // Corrected to include @Andy's edits and various comments on Stack Overflow
          data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF));
          sum += data;
          // 1's complement carry bit correction in 16-bits (detecting sign extension)
          if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
          }
    
          i += 2;
          length -= 2;
        }
    
        // Handle remaining byte in odd length buffers
        if (length > 0) {
          // Corrected to include @Andy's edits and various comments on Stack Overflow
          sum += (buf[i] << 8 & 0xFF00);
          // 1's complement carry bit correction in 16-bits (detecting sign extension)
          if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
          }
        }
    
        // Final 1's complement value correction to 16-bits
        sum = ~sum;
        sum = sum & 0xFFFF;
        return sum;
    
      }
    
    }
    

    Then the unit test in JUnit4

    package org.example.checksum;
    
    import org.junit.Test;
    
    import static junit.framework.Assert.assertEquals;
    
    public class InternetChecksumTest {
      @Test
      public void simplestValidValue() {
        InternetChecksum testObject = new InternetChecksum();
    
        byte[] buf = new byte[1]; // should work for any-length array of zeros
        long expected = 0xFFFF;
    
        long actual = testObject.calculateChecksum(buf);
    
        assertEquals(expected, actual);
      }
    
      @Test
      public void validSingleByteExtreme() {
        InternetChecksum testObject = new InternetChecksum();
    
        byte[] buf = new byte[]{(byte) 0xFF};
        long expected = 0xFF;
    
        long actual = testObject.calculateChecksum(buf);
    
        assertEquals(expected, actual);
      }
    
      @Test
      public void validMultiByteExtrema() {
        InternetChecksum testObject = new InternetChecksum();
    
        byte[] buf = new byte[]{0x00, (byte) 0xFF};
        long expected = 0xFF00;
    
        long actual = testObject.calculateChecksum(buf);
    
        assertEquals(expected, actual);
      }
    
      @Test
      public void validExampleMessage() {
        InternetChecksum testObject = new InternetChecksum();
    
        // Berkley example http://www.cs.berkeley.edu/~kfall/EE122/lec06/tsld023.htm
        // e3 4f 23 96 44 27 99 f3
        byte[] buf = {(byte) 0xe3, 0x4f, 0x23, (byte) 0x96, 0x44, 0x27, (byte) 0x99, (byte) 0xf3};
    
        long expected = 0x1aff;
    
        long actual = testObject.calculateChecksum(buf);
    
        assertEquals(expected, actual);
      }
    
      @Test
      public void validExampleEvenMessageWithCarryFromRFC1071() {
        InternetChecksum testObject = new InternetChecksum();
    
        // RFC1071 example http://www.ietf.org/rfc/rfc1071.txt
        // 00 01 f2 03 f4 f5 f6 f7
        byte[] buf = {(byte) 0x00, 0x01, (byte) 0xf2, (byte) 0x03, (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7};
    
        long expected = 0x220d;
    
        long actual = testObject.calculateChecksum(buf);
    
        assertEquals(expected, actual);
    
      }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.