Java Tutorial/Data Type/Byte

Материал из Java эксперт
Перейти к: навигация, поиск

byte Array To Hex String

public class Main {
  public static void main(String arg[]) {
    byteArrayToHexString(("abc").getBytes());
  }
  public static String byteArrayToHexString(byte[] b) {
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (int i = 0; i < b.length; i++) {
      int v = b[i] & 0xff;
      if (v < 16) {
        sb.append("0");
      }
      sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
  }
}





Byte Range

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @version $Id: ByteRange.java 587751 2007-10-24 02:41:36Z vgritsenko $
 */
final public class ByteRange {
    
    private final long start;
    private final long end;
    
    public ByteRange(long start, long end) {
        this.start = start;
        this.end = end;
    }
    
    public ByteRange(String string) throws NumberFormatException {
        string = string.trim();
        int dashPos = string.indexOf("-");
        int length = string.length();
        if (string.indexOf(",") != -1) {
            throw new NumberFormatException("Simple ByteRange String contains a comma.");
        }
        if (dashPos > 0) {
            this.start = Integer.parseInt(string.substring(0, dashPos));
        } else {
            this.start = Long.MIN_VALUE;
        }
        if (dashPos < length - 1) {
            this.end = Integer.parseInt(string.substring(dashPos + 1, length));
        } else {
            this.end = Long.MAX_VALUE;
        }
        if (this.start > this.end) {
            throw new NumberFormatException("Start value is greater than end value.");
        }
    }
    
    public long getStart() {
        return this.start;
    }
    
    public long getEnd() {
        return this.end;
    }
    
    public long length() {
        return this.end - this.start + 1;
    }
    
    public ByteRange intersection(ByteRange range) {
        if (range.end < this.start || this.end < range.start) {
            return null;
        } else {
            long start = (this.start > range.start) ? this.start : range.start;
            long end = (this.end < range.end) ? this.end : range.end;
            return new ByteRange(start, end);
        }
    }

    public String toString() {
        return this.start + "-" + this.end;
    }
    
}





Compare Two Java byte Arrays Example

import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    byte[] a1 = new byte[] { 7, 25, 12 };
    byte[] a2 = new byte[] { 7, 25, 12 };
    System.out.println(Arrays.equals(a1, a2));
  }
}





Convert an UNSIGNED byte to a JAVA type

public class Main {
  public static void main(String args[]) {
    byte b1 = 127;
    System.out.println(b1);
    System.out.println(unsignedByteToInt(b1));
  }
  public static int unsignedByteToInt(byte b) {
    return (int) b & 0xFF;
  }
}





Convert byte[ ] array to String

public class Main {
    public static void main(String[] args) {
        byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
        String value = new String(byteArray);
        System.out.println(value);
    }
}
//WOW...





Convert Byte to numeric primitive data types example

public class Main {
  public static void main(String[] args) {
    Byte bObj = new Byte("10");
    byte b = bObj.byteValue();
    System.out.println(b);
    short s = bObj.shortValue();
    System.out.println(s);
    int i = bObj.intValue();
    System.out.println(i);
    float f = bObj.floatValue();
    System.out.println(f);
    double d = bObj.doubleValue();
    System.out.println(d);
    long l = bObj.longValue();
    System.out.println(l);
  }
}





Convert byte to String: Creating a byte array and passing it to the String constructor

public class Main {
    public static void main(String[] args) {
        byte b = 65;
        
        System.out.println(new String(new byte[] {b}));
    }
}
//A





Convert byte to String: Using simple concatenation with an empty String

public class Main {
    public static void main(String[] args) {
        byte b = 65;
        
        System.out.println(b + "");
    }
}
//65





Convert byte to String: Using the static toString method of the Byte class

public class Main {
    public static void main(String[] args) {
        byte b = 65;
        
        System.out.println(Byte.toString(b));
    }
}





Convert String to byte

public class Main {
  public static void main(String[] args) {
    String s = "65";
    byte b = Byte.valueOf(s);
    System.out.println(b);
    // Causes a NumberFormatException since the value is out of range
    System.out.println(Byte.valueOf("129"));
  }
}
/*
65
Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10
  at java.lang.Byte.parseByte(Byte.java:153)
  at java.lang.Byte.valueOf(Byte.java:184)
  at java.lang.Byte.valueOf(Byte.java:208)
  at Main.main(Main.java:11)
*/





Convert String to byte array

public class Main {
    public static void main(String[] args) {
        String stringToConvert = "this is a test";
        
        byte[] theByteArray = stringToConvert.getBytes();
        
        System.out.println(theByteArray.length);
    }
}
//14





hex String To Byte Array

public class Main {

  public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
      int index = i * 2;
      int v = Integer.parseInt(s.substring(index, index + 2), 16);
      b[i] = (byte) v;
    }
    return b;
  }
}





Java byte: byte is smallest Java integer type.byte is 8 bit signed type ranges from �128 to 127.

public class Main {
  public static void main(String[] args) {
    byte b1 = 100;
    byte b2 = 20;
    System.out.println("Value of byte variable b1 is :" + b1);
    System.out.println("Value of byte variable b1 is :" + b2);
  }
}
/*
Value of byte variable b1 is :100
Value of byte variable b1 is :20
*/





Min and Max values of datatype byte

public class Main {
    public static void main(String[] args) {
        System.out.println(Byte.MIN_VALUE);
        System.out.println(Byte.MAX_VALUE);
    }
}
/*
-128
127
*/





To convert a byte to it"s hexadecimal equivalent

public class Main {
  public static void main(String[] argv) {
    System.out.println(byteToHex((byte) 123));
  }
  public static String byteToHex(byte b) {
    int i = b & 0xFF;
    return Integer.toHexString(i);
  }
}
//7b





Use Byte constructor to convert byte primitive type to Byte object

public class Main {
  public static void main(String[] args) {
    byte i = 10;
    
    Byte bObj = new Byte(i);
    System.out.println(bObj);
  }
}





Use toString method of Byte class to convert Byte into String

public class Main {
  public static void main(String[] args) {
    Byte bObj = new Byte("10");
    
    String str = bObj.toString();
    System.out.println(str);
  }
}





Using byte data type



public class MainClass {
  public static void main(String[] arg) {
    byte luckyNumber = 7;
    System.out.println(luckyNumber);
  }
}



7