---
title: "Java网络基本操作"
author: "280862132"
date: "2013-01-11T11:12:25Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-01-11T11:12:25Z"
id: 1768012
url: "https://280862132.iteye.com/blog/1768012"
---

**网络来源: http://cuisuqiang.iteye.com/blog/1695498**
获取一个 Byte 的各个 Bit 值
1. bit：位
    一个二进制数据0或1，是1bit；
2. byte：字节
    存储空间的基本计量单位，如：MySQL中定义 VARCHAR(45)  即是指 45个字节；
    1 byte = 8 bit
3. 一个英文字符占一个字节；
    1 字母 = 1 byte = 8 bit
4. 一个汉字占2个字节；
    1 汉字 = 2 byte = 16 bit
byte：一个字节（8位）（-128~127）（-2的7次方到2的7次方-1）
short：两个字节（16位）（-32768~32767）（-2的15次方到2的15次方-1）
int：四个字节（32位）（一个字长）（-2147483648~2147483647）（-2的31次方到2的31次方-1）
long：八个字节（64位）（-9223372036854774808~9223372036854774807）（-2的63次方到2的63次方-1）
float：四个字节（32位）（3.402823e+38 ~ 1.401298e-45）（e+38是乘以10的38次方，e-45是乘以10的负45次方）
double：八个字节（64位）（1.797693e+308~ 4.9000000e-324
 
Java中数据流的操作很多都是到byte的，但是在许多底层操作中是需要根据一个byte中的bit来做判断！
Java中要根据byte获得bit就要进行一些位操作，不过为了使用我直接给出解决方案，至于位操作的一些内容，回头再说！

package com.test;
import java.util.Arrays;
public class T {
	/**
	 * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
	 */
	public static byte getBooleanArray(byte b) {
		byte array = new byte;
		for (int i = 7; i >= 0; i--) {
			array* = (byte)(b & 1);
			b = (byte) (b >> 1);
		}
		return array;
	}
	/**
	 * 把byte转为字符串的bit
	 */
	public static String byteToBit(byte b) {
		return ""
				+ (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
				+ (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
				+ (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
				+ (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
	}
	public static void main(String args) {
		byte b = 0x35; // 0011 0101
		// 输出 
		System.out.println(Arrays.toString(getBooleanArray(b)));
		// 输出 00110101
		System.out.println(byteToBit(b));
		// JDK自带的方法，会忽略前面的 0
		System.out.println(Integer.toBinaryString(0x35));
	}
}

 输出内容就是各个 bit 位的 0 和 1 值！
 
根据各个Bit的值，返回byte的代码：

/**
 * 二进制字符串转byte
 */
public static byte decodeBinaryString(String byteStr) {
	int re, len;
	if (null == byteStr) {
		return 0;
	}
	len = byteStr.length();
	if (len != 4 && len != 8) {
		return 0;
	}
	if (len == 8) {// 8 bit处理
		if (byteStr.charAt(0) == '0') {// 正数
			re = Integer.parseInt(byteStr, 2);
		} else {// 负数
			re = Integer.parseInt(byteStr, 2) - 256;
		}
	} else {// 4 bit处理
		re = Integer.parseInt(byteStr, 2);
	}
	return (byte) re;
}