How to convert a Binary String to a base 10 integer in Java(如何在 Java 中将二进制字符串转换为以 10 为底的整数)
问题描述
我有一个表示二进制数(不带前导零)的字符串数组,我想将其转换为相应的以 10 为基数的数字.考虑:
I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:
binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary 11 becomes integer 3 etc.
最好的方法是什么?我一直在探索 java.lang.number.* 却没有找到直接的转换方法.Integer.parseInt(b) 产生一个与字符串相等的整数...例如,1001 变为 1,001 而不是 9...并且似乎不包含输出基数的参数.toBinaryString 转换方向错误.我怀疑我需要进行多步转换,但似乎找不到正确的方法或子类组合.我也不确定前导零或缺少前导零会在多大程度上成为问题.有人有什么好的方向可以指点我吗?
What's the best way to proceed? I've been exploring java.lang.number.* without finding a direct conversion method. Integer.parseInt(b) yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. toBinaryString does the conversion the wrong direction. I suspect I'll need to do a multistep conversion, but can't seem to find the right combination of methods or subclasses. I'm also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?
推荐答案
你需要指定基数.Integer#parseInt() 的重载允许您这样做.
You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.
int foo = Integer.parseInt("1001", 2);
这篇关于如何在 Java 中将二进制字符串转换为以 10 为底的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中将二进制字符串转换为以 10 为底的
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
