---
title: "进制转换问题"
author: "mousepc"
date: "2012-07-02T23:47:17Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-07-03T15:02:23Z"
id: 1575044
url: "https://mousepc.iteye.com/blog/1575044"
---

不知道写的对不对，有不对的地方可以向我指出来。

```
import java.util.Stack;

/**
 * 编写一个程序，它先将键盘上输入的一个字符串转换成十进制整数，然后打印出这个十进制整数对应的二进制形式。
 * 这个程序要考虑输入的字符串不能转换成一个十进制整数的情况，并对转换失败的原因要区分出是数字太大，还是其中包含有非数字字符的情况。
 * 提示：十进制数转二进制数的方式是用这个数除以2
 * ，余数就是二进制数的最低位，接着再用得到的商作为被除数去除以2，这次得到的余数就是次低位，如此循环，直到被除数为0为止
 * 。其实，只要明白了打印出一个十进制数的每一位的方式（不断除以10，得到的余数就分别是个位，十位，百位），就很容易理解十进制数转二进制数的这种方式。
 * @author manager
 * 
 */
public class Demo {

	public static void main(String[] args) {
		String param = "9876543210";
		Integer num = null;
		Stack<Integer> stack = new Stack<Integer>();

		try {
			num = Integer.valueOf(param);
			while (num > 0) {
				int b = num % 2;
				stack.add(b);
				num >>>= 1;// 无符号右移1位，相当于num = num / 2;只不过效率更高
			}
			toBinaryString(stack);
			// 也可以转为Integer之后，直接用Integer.toBinaryString(num)转为2进制，不过这不是题目的本意。
		} catch (Exception e) {
			boolean check = false;
			for (int i = 0; i < param.length(); i++) {
				char c = param.charAt(i);
				if (c < 48 || c > 57) {
					check = true;
					break;
				}
			}

			if (check) {
				System.out.println("存在非数字字符。");
			} else {
				System.out.println("数字太大。");
			}
		}
	}

	public static void toBinaryString(Stack<Integer> stack) {
		StringBuilder sb = new StringBuilder();
		while (!stack.empty()) {
			sb.append(stack.pop());
		}
		System.out.println(sb.toString());
	}
}
```