1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】文字列をString型からbyte型に変換する方法

Last updated at Posted at 2020-12-28

プログラミング勉強日記

2020年12月28日
今日はJavaで文字列をbyte型に変換する方法を知ったのでそれをまとめる。

byte型とは

 プリミティブ型のひとつで、8ビットまでの値を格納する。1ビットは0または1なので、1byteでは00000000から11111111までのビット配列を表現できる。byte型は符号つきで負の値もとるので、 -128 から 127 まで値をとる。
 画像ファイルや音声ファイル、文字列も内部ではbyteの集合体なので、byte型変数を単体で扱うというよりも、byte配列としてバイナリデータの集まりとして、利用されることが多い。

String型からbyte型に変換する方法

 getBytes()メソッドを使用する。getBytes()メソッドは文字列をbyteの集合体に変換して、byte配列として返す。

基本的な書き方
str.getBytes("エンコード");
サンプルコード

public class Sample {
  public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException {

    String str = "変換したい文字列";
    byte[] def = str.getBytes();
    byte[] utf8 = str.getBytes("UTF-8");
    byte[] utf16 = str.getBytes("UTF-16");

    System.out.println(Arrays.toString(def));
    System.out.println(Arrays.toString(utf8));
    System.out.println(Arrays.toString(utf16));

  }

}
実行結果
[-27, -92, -119, -26, -113, -101, -29, -127, -105, -29, -127, -97, -29, -127, -124, -26, -106, -121, -27, -83, -105, -27, -120, -105]
[-27, -92, -119, -26, -113, -101, -29, -127, -105, -29, -127, -97, -29, -127, -124, -26, -106, -121, -27, -83, -105, -27, -120, -105]
[-2, -1, 89, 9, 99, -37, 48, 87, 48, 95, 48, 68, 101, -121, 91, 87, 82, 23]

参考文献

Javaで文字列をString型からbyte型へ変換する方法を現役エンジニアが解説【初心者向け】

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?