如何在字符串中打印第一个字符的二进制表示 [英] How do I print the binary representation of the first character in a string

查看:155
本文介绍了如何在字符串中打印第一个字符的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索文件中数据的二进制值。所以我写了以下代码:

i want to retrieve the binary values of the data in the file. so i have written the following the code:

while ((fileData = br.readLine()) != null) {
  byte b[] = fileData.getBytes("UTF-8");
  BigInteger bi = new BigInteger(b);
  String s = bi.toString(2);
  System.out.println("Original message in binary: " + s);
  System.out.println("Original message length: " + s.length());
}

输出:

abca (this is the data in a text file)
Original message in binary: <here>1100001011000100110001101100001
Original message length: 31

一切都很好,但是当我打印二进制格式的数据时,我无法打印第一位(< here> )任何人都可以帮助我吗?

Everything is fine but while i am printing the data in binary format i am not able to print the first bit (<here>) can anyone help me?

推荐答案

对于第一个角色:

s.charAt(0);






编辑:
如果你想打印第一个字节的二进制表示,那么试试这个:


If you want to print the binary representation of first byte then try this:

    String str = Integer.toBinaryString("abca".getBytes("UTF-8")[0]);
    System.out.println(str);

编辑2:
尝试使用前导零。

EDIT 2: Try this for leading zeroes.

static String addLeadingZeroes(String s) {
    int zeroes = s.length() % 8;
    byte[] bzero = new byte[8 - zeroes];
    Arrays.fill(bzero, (byte)0x30);
    return new StringBuilder(new String(bzero)).append(s).toString();
}

并致电

System.out.println("Original message in binary: "+ addLeadingZeroes(s));

这篇关于如何在字符串中打印第一个字符的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆