Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by daniel.peczkowski on 2017-05-24.
- */
- public class ByteDataString implements Cloneable{
- public static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
- public final static char PAGE = 0xE100;//Custom symbols
- public final static String PAGE_STRING = "E1";
- private final StringBuilder data = new StringBuilder();
- public ByteDataString() {}
- public ByteDataString(ByteDataString bds){
- append(bds);
- }
- public ByteDataString(byte... bytes) {
- append(bytes);
- }
- public ByteDataString(char... chars) {
- append(chars);
- }
- public ByteDataString(String string, boolean hex) {
- append(string, hex);
- }
- @Override
- protected ByteDataString clone() {
- return new ByteDataString(this);
- }
- public StringBuilder getDataCopy() {
- return new StringBuilder(data);
- }
- public StringBuilder getDataObject() {
- return data;
- }
- public ByteDataString append(ByteDataString bds){
- data.append(bds.data);
- return this;
- }
- public ByteDataString append(byte... bytes) {
- char[] chars = new char[bytes.length];
- for (int i = 0; i < chars.length; i++) {
- chars[i] = (char) (0xFF & bytes[i]);
- if (chars[i] < 0x20 || chars[i] >= 0x7f) {
- chars[i] |= PAGE;
- }
- }
- data.append(chars);
- return this;
- }
- public ByteDataString append(char... chars) {
- for (int i = 0; i < chars.length; i++) {
- chars[i] &= 0xFF;
- if (chars[i] < 0x20 || chars[i] >= 0x7f) {
- chars[i] |= PAGE;
- }
- }
- data.append(chars);
- return this;
- }
- public ByteDataString append(String string, boolean hex) {
- if (hex) {
- if ((string.length() & 1) == 1) throw new Error("Invalid length of String: " + string);
- char[] chars = new char[string.length() >>> 1];
- for (int i = 0; i < chars.length; i++) {
- chars[i] = (char) ((Character.digit(string.charAt(i << 1), 16) << 4)
- + Character.digit(string.charAt((i << 1)+1), 16));
- if (chars[i] < 0x20 || chars[i] >= 0x7f) {
- chars[i] |= PAGE;
- }
- }
- data.append(chars);
- return this;
- }
- return append(string.toCharArray());
- }
- @Override
- public String toString() {
- return data.toString();
- }
- public String toMultilineString() {
- return data.toString().replaceAll("\\u"+PAGE_STRING+"0A", "\n");
- }
- public String toHexString(boolean whiteSpaces, boolean lines) {
- StringBuilder result = new StringBuilder();
- for (int i = 0; i < data.length(); ++i) {
- result.append(HEX_CHARS[(data.charAt(i) & 0xF0) >>> 4]);
- result.append(HEX_CHARS[data.charAt(i) & 0x0F]);
- if (whiteSpaces) {
- if (lines && (i & 0xF) == 0xF)
- result.append("\n");
- else
- result.append(" ");
- }
- }
- return result.toString();
- }
- public byte[] toBytes() {
- byte[] bytes = new byte[data.length()];
- for (int i = 0; i < bytes.length; i++) {
- bytes[i] = (byte) (data.charAt(i) & 0xff);
- }
- return bytes;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement