您的位置:首页 > 其它

比特位操作——二进制表示

2017-06-27 19:23 232 查看
转自:http://blog.csdn.net/shinanhualiu/article/details/50405295

给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 “ERROR”。

样例 

n = “3.72”, 返回 “ERROR”.

n = “3.5”, 返回 “11.1”.
public class BinaryRepresentation {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(binaryRepresentation("6.125"));
}

//将整数装换成二进制
public static String getIntBin(int n){

StringBuilder res=new StringBuilder();

if(n==0)
return "0";
while(n!=0){
res.append(n%2);
n/=2;
}
return res.reverse().toString();  //要反转
}

//将小数部分转换成二进制
public static String getDoubleBin(double n){

StringBuilder res=new StringBuilder();
if(n==0.0)
return "0";
while(n!=0.0){
//最好把这个判断放在while里面,如果放到while外面的话,可能会因为while死循环而无法执行
if(res.length()>32){
return "ERROR";
}
double ans=n*2;
res.append((int)ans);
n=ans-(int)ans;
}

return res.toString();

}

//将输入数据进行拆分
public static String binaryRepresentation(String n){

if(n.length()==0||n==null)
return "0";

int index=n.indexOf(".");
int inter=0;
double d=0;

if(index!=-1){  //等于-1表示不存在这样的index
inter=Integer.parseInt(n.substring(0,index));
d=Double.parseDouble(n.substring(index));
}
else{
inter=Integer.parseInt(n);
}
StringBuilder res=new StringBuilder();
res.append(getIntBin(inter));

if(d==0.0){
return res.toString();
}
res.append(".");
String tmp=getDoubleBin(d);
if(tmp.equals("ERROR"))
return tmp;

return res.append(tmp).toString();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐