首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

用两种编程步骤求存储每种Java基本整数类型所需要的位数(不考虑符号)

2012-10-25 
用两种编程方法求存储每种Java基本整数类型所需要的位数(不考虑符号)1.用位移操作import junit.framework.

用两种编程方法求存储每种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);}}



2.用数据流

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();}}

热点排行