把 b = (long)a & 0x000000111111; 改为 b = (long)(a & 0x00000000FFFFFFFF);
刚才没看清楚,应该是 b = (long)(0x00000000FFFFFFFF & ((long)(a * 10000))); c = (short)b;
public class type{ public static void main(String[] args) { double a = 1234.5678; long b = 0; b = (long)Math.floor(a); System.out.println(b);//以上是第一部分double temp = 0; temp = (a - b) * 10000;short c = 0; c = (short)Math.floor(temp); System.out.println(c); //我不会用位的控制计算这个问题,希望那位同仁告知谢谢了 }} 我找到答案了写出来大家看看有没有更好的方案。
b = (long)a & 0x000000111111;
改为
b = (long)(a & 0x00000000FFFFFFFF);
b = (long)(0x00000000FFFFFFFF & ((long)(a * 10000)));
c = (short)b;
public static void main(String[] args)
{ double a = 1234.5678;
long b = 0;
b = (long)Math.floor(a);
System.out.println(b);//以上是第一部分double temp = 0;
temp = (a - b) * 10000;short c = 0;
c = (short)Math.floor(temp);
System.out.println(c); //我不会用位的控制计算这个问题,希望那位同仁告知谢谢了
}}
我找到答案了写出来大家看看有没有更好的方案。
你的办法没成功我还想不到
12345678 & 0x00000000FFFFFFFF
前者的低4位字节并不是5678,所以并不能得到预期的结果,还是通过普通方法实现吧
b = ((long)(a * 10000)) % 10000 * 10000
public static void main(String[] args) {
double a = 1234.5678;
System.out.println(trunc(a));
System.out.println(getDec(a, 4));
} // 仅取得整数部份
static long trunc(double a) {
if ((a < 0) && ((long)Math.floor(a) < a)) {
return (long)Math.floor(a) + 1;
}
else {
return (long)Math.floor(a);
}
} // 取得小数部份,参数len为要取小数的位数
static long getDec(double a, int len) {
double b = Math.abs(a) - Math.abs(trunc(a));
if ((b == 0) ||(len <= 0)) {
return 0;
}
String temp = String.valueOf(b);
String str1 = temp.substring(2);
if (str1.length() < len) {
return Long.parseLong(str1.substring(0));
}else
{
return Long.parseLong(str1.substring(0, len));
}
}}