【问题标题】:How to convert a Byte array to an integer and then into a string, to display the integer value?如何将 Byte 数组转换为整数,然后转换为字符串,以显示整数值?
【发布时间】:2011-12-14 08:41:55
【问题描述】:

我正在尝试获取字节并将它们显示为 android 中的整数。我正在使用蓝牙聊天作为模板,并且正在从蓝牙设备发送数据,该设备工作正常且显示正常。现在,我不想显示正在发送的字节的字符集,而是显示整数值。这是蓝牙聊天开发者代码中 Handle 的代码。

byte[] writeBuf = (byte[]) msg.obj;

// construct a string from the buffer
String writeMessage = new String(writeBuf);

mConversationArrayAdapter.add("Me:  " + writeMessage);

我尝试将字节数组设为整数数组,但它可以工作,但我无法将整数数组转换为字符串...有人可以帮忙吗?

【问题讨论】:

  • “整数值”是什么意思? ASCII码?数字转换,“0” -> 0,“1” -> 1,等等?

标签: java string integer bytearray byte


【解决方案1】:

假设您知道字节顺序(大端与小端),您可以使用 ByteBuffer

byte[] writeBuf = (byte[]) msg.obj;

// construct a string from the buffer
String writeMessage = String.valueOf(ByteBuffer.wrap(writeBuf).getInt()));

如果你想要小端,你可以使用.order(ByteOrder.LITTLE_ENDIAN)

【讨论】:

  • +1 非常酷。我以前没用过ByteBuffer。看起来真的有助于避免处理byte[] 的痛苦和代码膨胀。附言找个时间选个头像吧!
  • 类似地,您可以获得 (byte)、getLong、getDouble、getFloat、getShort 等以及这些的组合(您可以将 byte[] 与数据类型组合)您还可以构建 byte[ ] 也来自基元。
猜你喜欢
  • 1970-01-01
  • 2019-10-16
  • 2016-01-06
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
相关资源
最近更新 更多