Java无符号整数转化二进制、十六进制字符串

package canghailan.util;
02  
03 /**
04  * @author canghailan 2012-03-02 21:31
05  */
06 public class Bytes {
07     private static final char[] DIGITS = {
08             '0''1''2''3''4''5''6''7''8''9''a''b''c','d''e''f'
09     };
10  
11     public static String toBinaryString(byte b) {
12         int u = toUnsigned(b);
13         return new String(new char[]{
14                 DIGITS[(u >>> 7) & 0x1],
15                 DIGITS[(u >>> 6) & 0x1],
16                 DIGITS[(u >>> 5) & 0x1],
17                 DIGITS[(u >>> 4) & 0x1],
18                 DIGITS[(u >>> 3) & 0x1],
19                 DIGITS[(u >>> 2) & 0x1],
20                 DIGITS[(u >>> 1) & 0x1],
21                 DIGITS[u & 0x1]
22         });
23     }
24  
25     public static String toBinaryString(byte... bytes) {
26         char[] buffer = new char[bytes.length * 8];
27         for (int i = 0, j = 0; i < bytes.length; ++i) {
28             int u = toUnsigned(bytes[i]);
29             buffer[j++] = DIGITS[(u >>> 7) & 0x1];
30             buffer[j++] = DIGITS[(u >>> 6) & 0x1];
31             buffer[j++] = DIGITS[(u >>> 5) & 0x1];
32             buffer[j++] = DIGITS[(u >>> 4) & 0x1];
33             buffer[j++] = DIGITS[(u >>> 3) & 0x1];
34             buffer[j++] = DIGITS[(u >>> 2) & 0x1];
35             buffer[j++] = DIGITS[(u >>> 1) & 0x1];
36             buffer[j++] = DIGITS[u & 0x1];
37         }
38         return new String(buffer);
39     }
40  
41     public static String toHexString(byte b) {
42         int u = toUnsigned(b);
43         return new String(new char[]{
44                 DIGITS[u >>> 4],
45                 DIGITS[u & 0xf]
46         });
47     }
48  
49     public static String toHexString(byte... bytes) {
50         char[] buffer = new char[bytes.length * 2];
51         for (int i = 0, j = 0; i < bytes.length; ++i) {
52             int u = toUnsigned(bytes[i]);
53             buffer[j++] = DIGITS[u >>> 4];
54             buffer[j++] = DIGITS[u & 0xf];
55         }
56         return new String(buffer);
57     }
58  
59     private static int toUnsigned(byte b) {
60         return b < 0 ? b + 256 : b;
61     }
62 }


1 public static void main(String[] args) throws Exception {
2     byte[] bytes = ByteBuffer.allocate(8).putLong(Long.MAX_VALUE).array();
3     System.out.println(Bytes.toHexString(bytes));
4 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值