Java基础-Byte类源码

package java.lang;

public final class Byte extends Number implements Comparable<Byte> {

    // 定义Byte对象的最小值:-128
    public static final byte   MIN_VALUE = -128;

    // 定义Byte对象的最大值:127
    public static final byte   MAX_VALUE = 127;

    /**
     * 表示是基本类型byte对应的对象
     */
    @SuppressWarnings("unchecked")
    public static final Class<Byte>  TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");

    public static String toString(byte b) {
        return Integer.toString((int)b, 10);
    }

    // Byte对象的缓存池 -128 - 127 之间的数值,在自动装箱的时候会自动获取缓存中的对象,超出范围则创建新的对象。
    private static class ByteCache {
        private ByteCache(){}

        // 建立缓存数组,因为byte最多128*2个值(-(-128)表示负数个数,127表示正数个数,1表示0的个数)
        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
        	// 缓存初始化,范围是-128到127
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

    // 根据基本类型byte值从缓存数组中获取对应Byte对象的值(因为缓存数组中有负数,所以要加上128)
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

    // 将radix进制的String类型数字s,转换为10进制byte数字
    public static byte parseByte(String s, int radix)
        throws NumberFormatException {
        int i = Integer.parseInt(s, radix);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                "Value out of range. Value:\"" + s + "\" Radix:" + radix);
        return (byte)i;
    }

    // String -> byte 默认String为10进制数字
    public static byte parseByte(String s) throws NumberFormatException {
        return parseByte(s, 10);
    }

    // 返回一个十进制Byte对象,值为radix进制的s转化为10进制
    public static Byte valueOf(String s, int radix)
        throws NumberFormatException {
        return valueOf(parseByte(s, radix));
    }

    // String -> Byte  默认String为10进制数字
    public static Byte valueOf(String s) throws NumberFormatException {
        return valueOf(s, 10);
    }

    // 根据String返回一个Byte对象
    public static Byte decode(String nm) throws NumberFormatException {
        int i = Integer.decode(nm);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                    "Value " + i + " out of range from input " + nm);
        return valueOf((byte)i);
    }

    // 用byte存储数据
    private final byte value;

    // byte -> Byte
    public Byte(byte value) {
        this.value = value;
    }

    // String -> Byte
    public Byte(String s) throws NumberFormatException {
        this.value = parseByte(s, 10);
    }

    // 以byte类型返回Byte的值
    public byte byteValue() {
        return value;
    }

    // 以short类型返回Byte的值
    public short shortValue() {
        return (short)value;
    }

    // 以int类型返回Byte的值
    public int intValue() {
        return (int)value;
    }

    // 以long类型返回Byte的值
    public long longValue() {
        return (long)value;
    }

    // 以float类型返回Byte的值
    public float floatValue() {
        return (float)value;
    }

    // 以double类型返回Byte的值
    public double doubleValue() {
        return (double)value;
    }

    // 以String类型返回Byte的值
    public String toString() {
        return Integer.toString((int)value);
    }

    // 返回hash值
    @Override
    public int hashCode() {
        return Byte.hashCode(value);
    }

    // 返回hash值
    public static int hashCode(byte value) {
        return (int)value;
    }

    // 判断两个Byte对象的值是否相等
    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }

    // 比较当前Byte对象与另一Byte对象的差值,当前对象-参数对象
    public int compareTo(Byte anotherByte) {
        return compare(this.value, anotherByte.value);
    }
    
    public static int compare(byte x, byte y) {
        return x - y;
    }

   /**
    *	将byte通过无符号转换转换为int
    *	0xff -> 255 -> 11111111
    *	& 两个数都转为二进制,然后从高位开始比较,如果两个数都为1则为1,否则为0。
    * 	将一个有符号位的byte数值,转换为无符号位对应的数值
    *	运行过程:x -> x的2进制补码 与 0xff进行 &操作得出结果。
			例如  x = -123 	00000000 00000000 00000000 10000101
			0xff=		   	00000000 00000000 00000000 11111111
							00000000 00000000 00000000 10000101 = 133
    */
    public static int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }


    // 将byte通过无符号转换转换为long
    public static long toUnsignedLong(byte x) {
        return ((long) x) & 0xffL;
    }


    // 表示一个byte值的二进制位数(补码)
    public static final int SIZE = 8;

    // 表示一个byte值的二进制字节数(补码)
    public static final int BYTES = SIZE / Byte.SIZE;

    // 用于序列化
    private static final long serialVersionUID = -7183698231559129828L;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我非常乐意为您提供有关Java串口通信的源代码。下面是一个简单的Java串口通信示例,其中包含了一些常见的串口通信操作。 ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; public class SerialCommunication { private SerialPort serialPort; private InputStream in; private OutputStream out; public void connect(String portName) throws Exception { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("无法连接到指定串口,该端口已经被占用."); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); in = serialPort.getInputStream(); out = serialPort.getOutputStream(); System.out.println("成功连接到串口."); } else { System.out.println("指定端口型错误."); } } } public void disconnect() { try { if (in != null) in.close(); if (out != null) out.close(); if (serialPort != null) serialPort.close(); System.out.println("已断开与串口的连接."); } catch (IOException e) { e.printStackTrace(); } } public void sendData(String data) throws IOException { out.write(data.getBytes()); out.flush(); System.out.println("已发送数据: " + data); } public String receiveData() throws IOException { byte[] buffer = new byte[1024]; int len = in.read(buffer); return new String(buffer, 0, len); } public static void main(String[] args) { try { SerialCommunication communication = new SerialCommunication(); communication.connect("COM1"); // 连接到COM1串口 communication.sendData("Hello, Serial Port!"); // 发送数据到串口 String receivedData = communication.receiveData(); // 接收来自串口的数据 System.out.println("接收到的数据: " + receivedData); communication.disconnect(); // 断开与串口的连接 } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码是一个简单的Java串口通信示例,其中包括了连接、断开连接、发送数据和接收数据等基本操作。在使用时,您需要添加对 `gnu.io` 包的依赖,并根据实际情况修改串口名称、波特率等参数。此外,还要确保您的计算机已经安装了正确的串口驱动程序。 请注意,此代码仅作为示例和参考之用。在实际开发中,建议使用现有的Java串口通信库,例如rxtx或jSerialComm,以简化开发过程并提供更多功能和稳定性。 ### 回答2: 串口通信是指通过串口进行数据传输的一种通信方式。在Java中,可以通过使用串口通信,来实现串口通信。下面是一个简化的串口通信源码示例: ```java import gnu.io.*; public class SerialPortCommunication { private SerialPort serialPort; // 串口对象 public SerialPortCommunication(String portName, int baudRate) { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); // 获取串口标识符 serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), 2000); // 打开串口 serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 设置串口参数 } catch (Exception e) { e.printStackTrace(); } } public void sendData(String data) { try { OutputStream outputStream = serialPort.getOutputStream(); // 获取串口输出流 byte[] bytes = data.getBytes(); outputStream.write(bytes); // 发送数据 } catch (Exception e) { e.printStackTrace(); } } public String receiveData() { String result = ""; try { InputStream inputStream = serialPort.getInputStream(); // 获取串口输入流 byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); // 读取串口数据 result = new String(buffer, 0, len); } catch (Exception e) { e.printStackTrace(); } return result; } public void close() { serialPort.close(); // 关闭串口 } } ``` 以上是一个简单的串口通信源码示例。通过该,你可以创建一个串口通信对象,并通过调用 `sendData()` 方法发送数据,通过调用 `receiveData()` 方法接收串口数据,通过 `close()` 方法关闭串口连接。在实际使用时,还需要根据具体项目需求进行更完善的错误处理和数据解析等功能。 ### 回答3: Java 串口通信源码实现主要是通过Java内置的Comm API或者使用第三方库来实现串口通信功能。 以下是一个简单的例子,展示了如何使用Comm API来进行串口通信: ```java import java.io.*; import java.util.*; import javax.comm.*; public class SerialCommunication { private static Enumeration portList; private static CommPortIdentifier portId; private static SerialPort serialPort; private static OutputStream outputStream; public static void main(String[] args) { try { // 获取可用的串口列表 portList = CommPortIdentifier.getPortIdentifiers(); // 遍历串口列表并找到需要使用的串口 while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { // 假设需要使用COM1串口 // 打开串口并设置参数 serialPort = (SerialPort) portId.open("SerialCommunication", 2000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 获取输出流,用于发送数据 outputStream = serialPort.getOutputStream(); // 发送数据到串口 outputStream.write("Hello, Serial!".getBytes()); serialPort.close(); // 关闭串口 } } } } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码使用了CommPortIdentifier来列举可用的串口,并通过SerialPort来打开指定的串口。然后,通过设置SerialPort的参数,例如波特率、数据位数、停止位和校验位等,在实际应用中应根据具体需求进行配置。接着,获取输出流并将数据发送到打开的串口。最后,关闭串口。 需要注意的是,以上代码仅为示例,实际使用时请根据具体的硬件设备和通信协议进行相应的修改和调整。 此外,还可以使用其他第三方库实现串口通信,例如RXTXcomm或者jSerialComm等。这些库提供了更多的功能和灵活性,让串口通信更加方便和易用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值