BCD码编程

#include <stdio.h>
#include <conio.h>
#include <string>
//c语言求 8421 BCD码
const char* BCDCode[] = {"0000","0001","0010", "0011","0100","0101","0110","0111","1000","1001","1010"};

std::string ConvertToBCD8421(int value)
{
	std::string strResult;
	if(value==0)
	{

		strResult=BCDCode[value];
	}
	for( int i=value%10;value!=0;i=value%10 )
	{        
		strResult = BCDCode[i] + strResult;
		value /= 10;
	}
	
	return strResult;
}
int main(void)
{
	for(int i=0;i<160;i++)
	{
		printf("%d=%s\n",i,ConvertToBCD8421(i).c_str());

	}	
	getch();
	return 0;
}
package com.jiepu.jfinal;

//java bcd码 8421码
public class App {
	public static void main(String[] args) {
		// Integer.MAX_VALUE
		for (int i = 0; i < 160; i++) {
			String vaule = toBCD(i);
			System.out.println(i + "=" + vaule);

		}
	}

	private static String toBCD(int num) {
		String numStr = Integer.toString(num);
		/* B:每一个十进制数用BCD码表示,则相当于按照十六进制进行parse */
		Integer bcdObj = Integer.parseInt(numStr, 16);
		int bcdValue = bcdObj.intValue();
		String bcd = Integer.toBinaryString(bcdValue);
		int len = bcd.length();
		int mod = len / 4;
		if(len%4 !=0)
		{
			mod=mod+1;
		}
		if (len <=4 * mod) {
			for (int j = 0; j < 4 * mod - len; j++) {
				bcd = "0" + bcd;
			}
		}
		return bcd;
	}
}


你可能感兴趣的:(BCD码编程)