在java里面如何把2进制专成8进制,或者10进制,有具体的函数么

bigsir 2005-06-16 07:53:33
可怜刚用java,binary的类型是什么都不知道
...全文
239 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wallex 2005-06-17
  • 打赏
  • 举报
回复
//import java.math.*;

BigInteger intA=new BigInteger("1010",2);
System.out.println("10: "+intA.toString(10)+"\t8: "+intA.toString(8)+"\t16: "+intA.toString(16));
Dan1980 2005-06-17
  • 打赏
  • 举报
回复
详细用法请参阅JDK文档.
Dan1980 2005-06-17
  • 打赏
  • 举报
回复
概念性错误!

计算机中的数据都是二进制形式存储的, 所谓的数据类型, 其实就是二进制数的位数不同而已, 比如一个int型的整数是一个32位的二进制数, 而一个short型是16位.

通常我们说的十进制, 八进制, 十六进制只是在字面形式上不同而已, 整数就是整数, 没有什么二进制型的, 十进制型的.

JAVA的Integer类提供了按照某种进制将字符串转化成整数的方法 - parseInt(), 也提供了其逆运算 - toString()系列, 比如, 将一个字符串"10"按照10进制转换成整数是10, 按照2进制转换则是3,

Integer.parseInt("10", 10) //returns 10
Integer.parseInt("10", 2) //returns 2

而数字按照某种进制转换成字符串道理也一样,

Integer.toString(10, 10) //returns "10"
Integer.toString(10, 2) //returns "1010"

注意, 这些方法都是静态的, Integer.toString()方法也不同于继承自Object的toString()方法.
bigsir 2005-06-17
  • 打赏
  • 举报
回复
wallex(兰舟催发), Dan1980(也该有一些作为了)
两位的代码我都试过了,可以满足我的功能要求,非常感谢2位

fanfan1984(凡凡) :
感谢你的帮助,虽然方向反了,但也对我很有用,省了我另外一个问题,谢谢


bigsir 2005-06-17
  • 打赏
  • 举报
回复
public class test4binary {
test4binary(){
}
public static void main(String[] args){

int m = 1;
int n = 1;

for (int i = 0; i<8 ; i++) {
m = n << 1 ;
n = m | 1;
System.out.printf("%s"+"\n",n);
}
byte bTemp = (byte) n ;
System.out.printf("%s",bTemp);

}
}
这个是我自己写的程序,调通了,意图是想往一个byte中的8个bit位付值,请大家看一下,有什么问题没有,这个在不同的环境下的执行效果应该是一致的吧,还有没有更合理的方法,毕竟位移不太爽利,谢谢!
fanfan1984 2005-06-16
  • 打赏
  • 举报
回复
Integer 类中有这样一些方法:
static String toBinaryString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 2.

static String toHexString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 16.

static String toOctalString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 8.
试试吧!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧