byte[] 和 long 型数据之间的转化,实现长整数类

题目

长整数问题, 参数类java.math.BigInteger,实现一个新的长整数类,要求类中的成员域只有byte[]mb_data;要求实现的成员方法是两个长整数类的加减乘除以及长整数与字符串之间相互转换。
不理解byte 为什么要 &0xff请参照我的博客:详解 & 0xff 的作用


package bytelong;

public class J_long {
	byte [] mb_data;
	
	public J_long() {}
	public J_long(long a) {
		mb_data=longToByte(a);
	}
	
	 public static byte[] longToByte(long number) {  
	        long temp = number;  
	        byte[] b = new byte[8];  
	        for (int i = 0; i < b.length; i++) {  
	            b[i] = new Long(temp & 0xff).byteValue();  
	            // 将最低位保存在最低位  
	            temp = temp >> 8;  
	            // 向右移8位  
	        }  
	        return b;  
	    } 
	
	public static long byteToLong(byte[] b) {  
        long s = 0;  
        long s0 = b[0] & 0xff;// 最低位  
        long s1 = b[1] & 0xff;  
        long s2 = b[2] & 0xff;  
        long s3 = b[3] & 0xff;  
        long s4 = b[4] & 0xff;// 最低位  
        long s5 = b[5] & 0xff;  
        long s6 = b[6] & 0xff;  
        long s7 = b[7] & 0xff;  
  
        // s0不变  
        s1 <<= 8;  
        s2 <<= 16;  
        s3 <<= 24;  
        s4 <<= 8 * 4;  
        s5 <<= 8 * 5;  
        s6 <<= 8 * 6;  
        s7 <<= 8 * 7;  
        s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;  
        return s;  
	}
	
    public long Add(long a ) {
    	return (a+byteToLong(mb_data));
    }

    public long Reduce(long a) {
    	return (byteToLong(mb_data)-a);
    }
    
    public long Multiply(long a) {
    	return (byteToLong(mb_data)*a);
    }
    
    public long Divide(long a) {
    	return (byteToLong(mb_data)/a);
    }
    
    public String toStr() {
    	return String.valueOf(byteToLong(mb_data));
    }
        

public static void main(String args[]) {
    long b=12 ;
	J_long a=new J_long(b);
	for(int i=0;i<8;i++)
	System.out.println(a.mb_data[i]);
	System.out.println(a.Add(3));
	System.out.println(a.Reduce(3));
	System.out.println(a.Multiply(3));
	System.out.println(a.Divide(4));
	System.out.println(a.toStr());
}

}

输出结果:
12
0
0
0
0
0
0
0
15
9
36
3
12

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值