java中bit操作常用技巧<二>

/**
 * @author canghailan 2012-03-02 21:31
 */
public class Bytes {
    private static final char[] DIGITS = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
 
    public static String toBinaryString(byte b) {
        int u = toUnsigned(b);
        return new String(new char[]{
                DIGITS[(u >>> 7) & 0x1],
                DIGITS[(u >>> 6) & 0x1],
                DIGITS[(u >>> 5) & 0x1],
                DIGITS[(u >>> 4) & 0x1],
                DIGITS[(u >>> 3) & 0x1],
                DIGITS[(u >>> 2) & 0x1],
                DIGITS[(u >>> 1) & 0x1],
                DIGITS[u & 0x1]
        });
    }
 
    public static String toBinaryString(byte... bytes) {
        char[] buffer = new char[bytes.length * 8];
        for (int i = 0, j = 0; i < bytes.length; ++i) {
            int u = toUnsigned(bytes[i]);
            buffer[j++] = DIGITS[(u >>> 7) & 0x1];
            buffer[j++] = DIGITS[(u >>> 6) & 0x1];
            buffer[j++] = DIGITS[(u >>> 5) & 0x1];
            buffer[j++] = DIGITS[(u >>> 4) & 0x1];
            buffer[j++] = DIGITS[(u >>> 3) & 0x1];
            buffer[j++] = DIGITS[(u >>> 2) & 0x1];
            buffer[j++] = DIGITS[(u >>> 1) & 0x1];
            buffer[j++] = DIGITS[u & 0x1];
        }
        return new String(buffer);
    }
 
    public static String toHexString(byte b) {
        int u = toUnsigned(b);
        return new String(new char[]{
                DIGITS[u >>> 4],
                DIGITS[u & 0xf]
        });
    }
 
    public static String toHexString(byte... bytes) {
        char[] buffer = new char[bytes.length * 2];
        for (int i = 0, j = 0; i < bytes.length; ++i) {
            int u = toUnsigned(bytes[i]);
            buffer[j++] = DIGITS[u >>> 4];
            buffer[j++] = DIGITS[u & 0xf];
        }
        return new String(buffer);
    }
 
    private static int toUnsigned(byte b) {
        return b < 0 ? b + 256 : b;
    }
}


转自:http://www.oschina.net/code/snippet_116768_9019


注释:研究下ByteBuffer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值