java - 从 inputStream 中读取字节的 Int 值

标签 java android byte

我正在尝试读取输入流中字节的 ASCII 值。我有以下代码

 int bd = 0;
 byte[] buffer = new byte[260];
 while (true) {
     try {
          if ((bd = inputStream.read(buffer, 0, buffer.length)) > 0) {
              Log.d("TAG", "Number of bytes from stream" + bd);
           }

为了读取字节值。我尝试了此示例中的以下方法之一 read byte value .

String s = new String(buffer,StandardCharsets.US_ASCII);

System.out.println("data from buffer s : " + s);
Result of s:"/9AAAAAAAAAAAAA=="
System.out.println("data from buffer s : " + parseInt(s)); -- error

String s2 = new String(buffer);
System.out.println("data from buffer s2: " + s2);
Result of s2: �@���������������

如何获取 int 的 ASCII 值?我尝试使用 parseInt(s) 将字符串转换为 Int,但我陷入了 NumberFormatException 错误

最佳答案

如何获取 int 的字节值?

首先将int转换为字符串

 int a = 454545454;
        String data = String.valueOf(a);
        try {
            byte[] bytesdata = data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

改变你的问题

将所有非数字替换为空白:剩余字符串仅包含数字。

Integer.parseInt(s.replaceAll("[\\D]", ""))

现在进一步查看 Get ASCII from int

关于java - 从 inputStream 中读取字节的 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291152/

相关文章:

java - 适用于 Android 的 OpenCV : Illegal Forward Reference

java - eclipse 无法在大型 android 文件上显示为 "build workspace"...?

java - 序列化和文件大小

c - 分组中的单独字节

java: 将文件解压成字符串太慢

java - diver.findElements 在 Selenium 中被挂起

java - 创建 WebMVCConfig 资源 [/com.chat.config/] 中定义的名称为 'resolver' 的 bean 时出错

android - 如何在 Android ImageView 中显示 .Gif 图像

java - 将 int 转换为 byte 时出现 BufferOverflowException

java - 当我重新打开应用程序时,如何检查上一个 session 中的线程是否仍在运行?