Wednesday 29 January 2020

Java: Check whether a number is 32 bit integer or not


A 32-bit signed integer can represent all of the integer values from -2147483648 to 2147483647

Following function takes a number and return true, if the number is in range of signed 32 bit integer.

public static boolean is32BitSignedInteger(long num) {
         return (num <= 2147483647) && (num >= -2147483648);
}

A 32-bit unsigned integer can represent all of the integer values from range is 0 through 4,294,967,295.

Following function takes a number and return true, if the number is in range of unsigned 32 bit integer.

public static boolean is32BitUnsignedInteger(long num) {
         return (num >= 0) && (num <= 4294967295l);
}

Find the below working application.

NumberUtil.java
package com.smaple.app.utils;

public class NumberUtil {

 public static boolean is32BitSignedInteger(long num) {
  return (num <= 2147483647) && (num >= -2147483648);
 }
 
 public static boolean is32BitUnsignedInteger(long num) {
  return (num >= 0) && (num <= 4294967295l);
 }
 
}


NumberUtilTest.java
package com.sample.app.utils;

import static org.junit.Assert.*;

import org.junit.Test;

import com.smaple.app.utils.NumberUtil;

public class NumberUtilTest {

 @Test
 public void is32BitSignedIntegerTest() {
  assertTrue(NumberUtil.is32BitSignedInteger(-2147483648));
  assertTrue(NumberUtil.is32BitSignedInteger(0));
  assertTrue(NumberUtil.is32BitSignedInteger(-10));
  assertTrue(NumberUtil.is32BitSignedInteger(100));
  assertTrue(NumberUtil.is32BitSignedInteger(2147483647));

  assertFalse(NumberUtil.is32BitSignedInteger(2147483648l));
  assertFalse(NumberUtil.is32BitSignedInteger(-2147483649l));
  assertFalse(NumberUtil.is32BitSignedInteger(21474836481l));
  assertFalse(NumberUtil.is32BitSignedInteger(-21474836491l));
 }

 @Test
 public void is32BitUnsignedInteger() {
  assertTrue(NumberUtil.is32BitUnsignedInteger(0));
  assertTrue(NumberUtil.is32BitUnsignedInteger(10));
  assertTrue(NumberUtil.is32BitUnsignedInteger(4294967295l));

  assertFalse(NumberUtil.is32BitUnsignedInteger(4294967296l));
  assertFalse(NumberUtil.is32BitUnsignedInteger(-1));
  assertFalse(NumberUtil.is32BitUnsignedInteger(-21474836491l));
 }
}


You may like

No comments:

Post a Comment