package com.szpg.plc.util;

public class Bytes {

	private byte[] buffer = null;

	public Bytes() {

	}

	public Bytes append(byte b) {
		byte[] nb = null;
		if (buffer == null) {
			nb = new byte[] { b };
		} else {
			nb = new byte[buffer.length + 1];
			for (int i = 0; i < buffer.length; i++) {
				nb[i] = buffer[i];
			}
			nb[nb.length - 1] = b;
		}
		buffer = nb;
		return this;
	}

	public Bytes append(byte[] bs) {
		if (bs == null)
			return this;
		byte[] nb = null;
		if (buffer == null) {
			buffer = bs;
		} else {
			nb = new byte[buffer.length + bs.length];
			for (int i = 0; i < buffer.length; i++) {
				nb[i] = buffer[i];
			}
			for (int i = 0; i < bs.length; i++) {
				nb[buffer.length + i] = bs[i];
			}
			buffer = nb;
		}
		return this;
	}

	public byte[] toBytes() {
		return buffer;
	}
	
	public byte[] toBytes(int l) {
		Bytes bs = new Bytes();
		
		for (int i = 0; i < l; i++) {
			if (i < buffer.length) {
				bs.append(buffer[i]);
			} else {
				bs.append((byte) 0x00);
			}
		}
		
		return bs.toBytes();
	}

	public static void main(String[] args) {
		Bytes bytes = new Bytes();
		int i = 0xf2;
		byte a = 0x68;
		byte[] b = new byte[] { 0x11, 0x22 };
		byte c = (byte) i;
		byte[] r = bytes.append(a).append(b).append(c).toBytes();
		System.out.println(r);
	}

}
