Java Tutorial/Data Type/String vs Byte Array

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

Construct string from subset of char array.

class SubStringCons {
  public static void main(String args[]) {
    byte ascii[] = { 65, 66, 67, 68, 69, 70 };
    String s1 = new String(ascii);
    System.out.println(s1);
    String s2 = new String(ascii, 2, 3);
    System.out.println(s2);
  }
}





Convert a byte array to a String with a hexidecimal format.

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   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.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
  Convert a byte array to a String with a hexidecimal format.
  The String may be converted back to a byte array using fromHexString.
  <BR>
  For each byte (b) two characaters are generated, the first character
  represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>), the second character
  represents the low nibble (<code>b & 0x0f</code>).
  <BR>
  The byte at <code>data[offset]</code> is represented by the first two characters in the returned String.
  @param  data  byte array
  @param  offset  starting byte (zero based) to convert.
  @param  length  number of bytes to convert.
  @return the String (with hexidecimal format) form of the byte array
*/
public static String toHexString(byte[] data, int offset, int length)
{
  StringBuffer s = new StringBuffer(length*2);
  int end = offset+length;
  for (int i = offset; i < end; i++)
  {
    int high_nibble = (data[i] & 0xf0) >>> 4;
    int low_nibble = (data[i] & 0x0f);
    s.append(hex_table[high_nibble]);
    s.append(hex_table[low_nibble]);
  }
  return s.toString();
}

}





Convert a hexidecimal string generated by toHexString() back into a byte array.

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   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.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
    Convert a hexidecimal string generated by toHexString() back
    into a byte array.
    @param s String to convert
    @param offset starting character (zero based) to convert.
    @param length number of characters to convert.
    @return the converted byte array. Returns null if the length is
    not a multiple of 2.
  */
  public static byte[] fromHexString(String s, int offset, int length)
  {
    if ((length%2) != 0)
      return null;
    byte[] byteArray = new byte[length/2];
    int j = 0;
    int end = offset+length;
    for (int i = offset; i < end; i += 2)
    {
      int high_nibble = Character.digit(s.charAt(i), 16);
      int low_nibble = Character.digit(s.charAt(i+1), 16);
      if (high_nibble == -1 || low_nibble == -1)
      {
        // illegal format
        return null;
      }
      byteArray[j++] = (byte)(((high_nibble << 4) & 0xf0) | (low_nibble & 0x0f));
    }
    return byteArray;
  }
}





Convert a string into a byte array in hex format.

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   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.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
      Convert a string into a byte array in hex format.
      <BR>
      For each character (b) two bytes are generated, the first byte 
      represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>),
      the second byte represents the low nibble (<code>b & 0x0f</code>).
      <BR>
      The character at <code>str.charAt(0)</code> is represented by the first two bytes 
      in the returned String.
      @param  str string 
      @param  offset  starting character (zero based) to convert.
      @param  length  number of characters to convert.
      @return the byte[]  (with hexidecimal format) form of the string (str) 
  */
  public static byte[] toHexByte(String str, int offset, int length)
  {
      byte[] data = new byte[(length - offset) * 2];
      int end = offset+length;
      for (int i = offset; i < end; i++)
      {
          char ch = str.charAt(i);
          int high_nibble = (ch & 0xf0) >>> 4;
          int low_nibble = (ch & 0x0f);
          data[i] = (byte)high_nibble;
          data[i+1] = (byte)low_nibble;
      }
      return data;
  }
}





Convert bytes to a base16 string.

/*
 * 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.    
 */
/**
 * Base 16 encoder.
 *
 * @author Marc Prud"hommeaux
 * @nojavadoc
 */
 class Base16Encoder {
    private final static char[] HEX = new char[]{
        "0", "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "A", "B", "C", "D", "E", "F" };
    /**
     * Convert bytes to a base16 string.
     */
    public static String encode(byte[] byteArray) {
        StringBuffer hexBuffer = new StringBuffer(byteArray.length * 2);
        for (int i = 0; i < byteArray.length; i++)
            for (int j = 1; j >= 0; j--)
                hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]);
        return hexBuffer.toString();
    }
    /**
     * Convert a base16 string into a byte array.
     */
    public static byte[] decode(String s) {
        int len = s.length();
        byte[] r = new byte[len / 2];
        for (int i = 0; i < r.length; i++) {
            int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1);
            if (digit1 >= "0" && digit1 <= "9")
                digit1 -= "0";
            else if (digit1 >= "A" && digit1 <= "F")
                digit1 -= "A" - 10;
            if (digit2 >= "0" && digit2 <= "9")
                digit2 -= "0";
            else if (digit2 >= "A" && digit2 <= "F")
                digit2 -= "A" - 10;
            r[i] = (byte) ((digit1 << 4) + digit2);
        }
        return r;
    }
}





Converts a hex string to a byte array.

/*   Copyright 2004 The Apache Software Foundation
 *
 *   Licensed 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.
 */
//xmlbeans
import java.io.UnsupportedEncodingException;
/**
 * format validation
 *
 * This class encodes/decodes hexadecimal data
 * @author Jeffrey Rodriguez
 * @version $Id: HexBin.java 125124 2005-01-14 00:23:54Z kkrouse $
 */
public class Main {
  static private final int  BASELENGTH   = 255;
  static private final int  LOOKUPLENGTH = 16;
  static private byte [] hexNumberTable    = new byte[BASELENGTH];
  static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH];

  static {
      for (int i = 0; i<BASELENGTH; i++ ) {
          hexNumberTable[i] = -1;
      }
      for ( int i = "9"; i >= "0"; i--) {
          hexNumberTable[i] = (byte) (i-"0");
      }
      for ( int i = "F"; i>= "A"; i--) {
          hexNumberTable[i] = (byte) ( i-"A" + 10 );
      }
      for ( int i = "f"; i>= "a"; i--) {
         hexNumberTable[i] = (byte) ( i-"a" + 10 );
      }
      for(int i = 0; i<10; i++ )
          lookUpHexAlphabet[i] = (byte) ("0"+i );
      for(int i = 10; i<=15; i++ )
          lookUpHexAlphabet[i] = (byte) ("A"+i -10);
  }

  /**
   * Converts a hex string to a byte array.
   */
  static public byte[] stringToBytes(String hexEncoded)
  {
      return decode(hexEncoded.getBytes());
  }
  static public byte[] decode(byte[] binaryData) {
      if (binaryData == null)
          return null;
      int lengthData   = binaryData.length;
      if (lengthData % 2 != 0)
          return null;
      int lengthDecode = lengthData / 2;
      byte[] decodedData = new byte[lengthDecode];
      for( int i = 0; i<lengthDecode; i++ ){
          if (!isHex(binaryData[i*2]) || !isHex(binaryData[i*2+1])) {
              return null;
          }
          decodedData[i] = (byte)((hexNumberTable[binaryData[i*2]] << 4) | hexNumberTable[binaryData[i*2+1]]);
      }
      return decodedData;
  }
  /**
   * byte to be tested if it is Base64 alphabet
   *
   * @param octect
   * @return
   */
  static boolean isHex(byte octect) {
      return (hexNumberTable[octect] != -1);
  }
}





Converts bytes to a hex string

/*   Copyright 2004 The Apache Software Foundation
 *
 *   Licensed 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.
 */
//xmlbeans
import java.io.UnsupportedEncodingException;
/**
 * format validation
 *
 * This class encodes/decodes hexadecimal data
 * @author Jeffrey Rodriguez
 * @version $Id: HexBin.java 125124 2005-01-14 00:23:54Z kkrouse $
 */
public class Main {
  static private final int  BASELENGTH   = 255;
  static private final int  LOOKUPLENGTH = 16;
  static private byte [] hexNumberTable    = new byte[BASELENGTH];
  static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH];

  static {
      for (int i = 0; i<BASELENGTH; i++ ) {
          hexNumberTable[i] = -1;
      }
      for ( int i = "9"; i >= "0"; i--) {
          hexNumberTable[i] = (byte) (i-"0");
      }
      for ( int i = "F"; i>= "A"; i--) {
          hexNumberTable[i] = (byte) ( i-"A" + 10 );
      }
      for ( int i = "f"; i>= "a"; i--) {
         hexNumberTable[i] = (byte) ( i-"a" + 10 );
      }
      for(int i = 0; i<10; i++ )
          lookUpHexAlphabet[i] = (byte) ("0"+i );
      for(int i = 10; i<=15; i++ )
          lookUpHexAlphabet[i] = (byte) ("A"+i -10);
  }
  /**
   * Converts bytes to a hex string
   */
  static public String bytesToString(byte[] binaryData)
  {
      if (binaryData == null)
          return null;
      return new String(encode(binaryData));
  }
  /**
   * array of byte to encode
   *
   * @param binaryData
   * @return return encode binary array
   */
  static public byte[] encode(byte[] binaryData) {
      if (binaryData == null)
          return null;
      int lengthData   = binaryData.length;
      int lengthEncode = lengthData * 2;
      byte[] encodedData = new byte[lengthEncode];
      for( int i = 0; i<lengthData; i++ ){
          encodedData[i*2] = lookUpHexAlphabet[(binaryData[i] >> 4) & 0xf];
          encodedData[i*2+1] = lookUpHexAlphabet[ binaryData[i] & 0xf];
      }
      return encodedData;
  }
}





Get 7-bit ASCII character array from input String.

/*
 Derby - Class org.apache.derby.iapi.util.PropertyUtil
 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.
 */
public class Main {

  /**
    Get 7-bit ASCII character array from input String.
    The lower 7 bits of each character in the input string is assumed to be
    the ASCII character value.
     Hexadecimal - Character
     | 00 NUL| 01 SOH| 02 STX| 03 ETX| 04 EOT| 05 ENQ| 06 ACK| 07 BEL|
     | 08 BS | 09 HT | 0A NL | 0B VT | 0C NP | 0D CR | 0E SO | 0F SI |
     | 10 DLE| 11 DC1| 12 DC2| 13 DC3| 14 DC4| 15 NAK| 16 SYN| 17 ETB|
     | 18 CAN| 19 EM | 1A SUB| 1B ESC| 1C FS | 1D GS | 1E RS | 1F US |
     | 20 SP | 21  ! | 22  " | 23  # | 24  $ | 25  % | 26  & | 27  " |
     | 28  ( | 29  ) | 2A  * | 2B  + | 2C  , | 2D  - | 2E  . | 2F  / |
     | 30  0 | 31  1 | 32  2 | 33  3 | 34  4 | 35  5 | 36  6 | 37  7 |
     | 38  8 | 39  9 | 3A  : | 3B  ; | 3C  < | 3D  = | 3E  > | 3F  ? |
     | 40  @ | 41  A | 42  B | 43  C | 44  D | 45  E | 46  F | 47  G |
     | 48  H | 49  I | 4A  J | 4B  K | 4C  L | 4D  M | 4E  N | 4F  O |
     | 50  P | 51  Q | 52  R | 53  S | 54  T | 55  U | 56  V | 57  W |
     | 58  X | 59  Y | 5A  Z | 5B  [ | 5C  \ | 5D  ] | 5E  ^ | 5F  _ |
     | 60  ` | 61  a | 62  b | 63  c | 64  d | 65  e | 66  f | 67  g |
     | 68  h | 69  i | 6A  j | 6B  k | 6C  l | 6D  m | 6E  n | 6F  o |
     | 70  p | 71  q | 72  r | 73  s | 74  t | 75  u | 76  v | 77  w |
     | 78  x | 79  y | 7A  z | 7B  { | 7C  | | 7D  } | 7E  ~ | 7F DEL|
   */
  public static byte[] getAsciiBytes(String input)
  {
    char[] c = input.toCharArray();
    byte[] b = new byte[c.length];
    for (int i = 0; i < c.length; i++)
      b[i] = (byte)(c[i] & 0x007F);
    return b;
  }

}





Get byte array from hex string

/*
 *  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. 
 *  
 */

/**
 * Various string manipulation methods that are more efficient then chaining
 * string operations: all is done in the same buffer without creating a bunch of
 * string objects.
 * 
 * @author 
 */
public class Main {
  /** lowerCase = "a" .. "z", "0".."9", "-" */
  private static final char[] LOWER_CASE =
      { 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0, "-",   0,   0, 
          "0", "1", "2", "3", "4", "5", "6", "7", 
          "8", "9",   0,   0,   0,   0,   0,   0, 
            0, "a", "b", "c", "d", "e", "f", "g", 
          "h", "i", "j", "k", "l", "m", "n", "o", 
          "p", "q", "r", "s", "t", "u", "v", "w", 
          "x", "y", "z",   0,   0,   0,   0,   0, 
            0, "a", "b", "c", "d", "e", "f", "g", 
          "h", "i", "j", "k", "l", "m", "n", "o", 
          "p", "q", "r", "s", "t", "u", "v", "w", 
          "x", "y", "z",   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0 
      };
  /**
   * Get byte array from hex string
   * 
   * @param hexString
   *            the hex string to convert to a byte array
   * @return the byte form of the hex string.
   */
  public static final byte[] toByteArray( String hexString )
  {
      int arrLength = hexString.length() >> 1;
      byte buf[] = new byte[arrLength];
      
      for ( int ii = 0; ii < arrLength; ii++ )
      {
          int index = ii << 1;
          
          String l_digit = hexString.substring( index, index + 2 );
          buf[ii] = ( byte ) Integer.parseInt( l_digit, 16 );
      }
      
      return buf;
  }
}





Gets a hex string from byte array.

/*
 *  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. 
 *  
 */

/**
 * Various string manipulation methods that are more efficient then chaining
 * string operations: all is done in the same buffer without creating a bunch of
 * string objects.
 * 
 * @author 
 */
public class Main {
  /**
   * Gets a hex string from byte array.
   * 
   * @param res
   *            the byte array
   * @return the hex string representing the binary values in the array
   */
  public static final String toHexString( byte[] res )
  {
      StringBuffer buf = new StringBuffer( res.length << 1 );
      
      for ( int ii = 0; ii < res.length; ii++ )
      {
          String digit = Integer.toHexString( 0xFF & res[ii] );
          
          if ( digit.length() == 1 )
          {
              digit = "0" + digit;
          }
          
          buf.append( digit );
      }
      return buf.toString().toUpperCase();
  }

}





Obtaining the Characters in a String as an Array of Bytes

public class MainClass {
  public static void main(String[] arg) {
    String text = "To be or not to be";        // Define a string
    byte[] textArray = text.getBytes();
    
    for(byte b: textArray){
      System.out.println(b);
      
    }
  }
}



84
111
32
98
101
32
111
114
32
110
111
116
32
116
111
32
98
101