「Java byte配列を16進数文字列に変換する」の版間の差分
ナビゲーションに移動
検索に移動
(ページの作成:「==Java byte配列を16進数文字列に変換する== [Java] public static String byteToString(byte[] bytes) { if (bytes == null) { return null; }…」) |
|||
| (同じ利用者による、間の2版が非表示) | |||
| 1行目: | 1行目: | ||
| − | ==Java byte配列を16進数文字列に変換する== | + | ==[[Java byte配列を16進数文字列に変換する]]== |
| − | [Java] | + | [[Java]] | |
public static String byteToString(byte[] bytes) { | public static String byteToString(byte[] bytes) { | ||
| 8行目: | 8行目: | ||
StringBuilder buf = new StringBuilder(bytes.length * 2); | StringBuilder buf = new StringBuilder(bytes.length * 2); | ||
| − | for (int i = 0; i | + | for (int i = 0; i < bytes.length; i++) { |
int d = bytes[i]; | int d = bytes[i]; | ||
| − | if (d | + | if (d < 0) { |
// byte型では128~255が負値になっているので補正 | // byte型では128~255が負値になっているので補正 | ||
d += 256; | d += 256; | ||
} | } | ||
| − | if (d | + | if (d < 16) { |
// 0~15は16進数で1けたになるので、2けたになるよう頭に0を追加 | // 0~15は16進数で1けたになるので、2けたになるよう頭に0を追加 | ||
buf.append("0"); | buf.append("0"); | ||
2020年2月16日 (日) 04:27時点における最新版
Java byte配列を16進数文字列に変換する
Java |
public static String byteToString(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
int d = bytes[i];
if (d < 0) {
// byte型では128~255が負値になっているので補正
d += 256;
}
if (d < 16) {
// 0~15は16進数で1けたになるので、2けたになるよう頭に0を追加
buf.append("0");
}
// 1バイトを16進数2けたで表示
buf.append(Integer.toString(d, 16));
}
return buf.toString();
}
© 2006 矢木浩人