java bcd 日期_java中BCD编码

Java中实现的BCD编码,供有兴趣的参考,欢迎批评指正

public class BCDCode

{

/**

*

*

* @param bcd 数字字符串

* @return

* @see [类、类#方法、类#成员]

*/

public static byte[] str2bcd(String bcd)

{

if (Global.isEmpty(bcd))

{

return null;

}

else

{

// 获取字节数组长度

int size = bcd.length() / 2;

int remainder = bcd.length() % 2;

// 存储BCD码字节

byte[] bcdByte = new byte[size + remainder];

// 转BCD码

for (int i = 0; i < size; i++)

{

int low = Integer.parseInt(bcd.substring(2 * i, 2 * i + 1));

int high = Integer.parseInt(bcd.substring(2 * i + 1, 2 * i + 2));

bcdByte[i] = (byte)((high << 4) | low);

}

// 如果存在余数,需要填F

if (remainder > 0)

{

int low = Integer.parseInt(bcd.substring(bcd.length() - 1));

bcdByte[bcdByte.length - 1] = (byte)((0xf << 4) | low);

}

// 返回BCD码字节数组

return bcdByte;

}

}

/**

*

*

* @param bcd 字节数组

* @return

* @see [类、类#方法、类#成员]

*/

public static String bcd2str(byte[] bcd)

{

if (null == bcd || bcd.length == 0)

{

return "";

}

else

{

// 存储转码后的字符串

StringBuilder sb = new StringBuilder();

// 循环数组解码

for (int i = 0; i < bcd.length; i++)

{

// 转换低字节

int low = (bcd[i] & 0x0f);

sb.append(low);

// 转换高字节

int high = ((bcd[i] & 0xf0) >> 4);

// 如果高字节等于0xf说明是补的字节,直接抛掉

if (high != 0xf)

{

sb.append(high);

}

}

// 返回解码字符串

return sb.toString();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值