用两种编程方法求存储每种Java基本整数类型所需要的位数(不考虑符号)
1.用位移操作
import junit.framework.TestCase;public class TestDataTypeSize extends TestCase{public void testLong(){long a= 0;int count = 0;while(a !=0){a = (a << 1);count++;}assertEquals(64, count);}public void testInt(){int a= 0;int count = 0;while(a !=0){a = (a << 1);count++;}assertEquals(32, count);}public void testShort(){short a = 0;int count = 0;while(a !=0){a = (short) (a << 1);count++;}assertEquals(16, count);}public void testByte(){byte a= 0;int count = 0;while(a !=0){a = (byte) (a << 1);count++;}assertEquals(8, count);}}
import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.IOException;import junit.framework.TestCase;public class TestDataTypeSize extends TestCase {public void testLong() throws IOException{ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);dataOutputStream.writeLong(0);assertEquals(8, byteArrayOutputStream.size());dataOutputStream.close();}public void testInt() throws IOException{ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);dataOutputStream.writeInt(0);assertEquals(4, byteArrayOutputStream.size());dataOutputStream.close();}public void testShort() throws IOException{ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);dataOutputStream.writeShort(0);assertEquals(2, byteArrayOutputStream.size());dataOutputStream.close();}public void testByte() throws IOException{ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);dataOutputStream.writeByte(0);assertEquals(1, byteArrayOutputStream.size());dataOutputStream.close();}}