【问题标题】:convert hex string to byte not byte array将十六进制字符串转换为字节而不是字节数组
【发布时间】:2015-01-15 23:41:30
【问题描述】:

我需要转换从颜色代码获得的十六进制

int color = singleColor.getColor();

                String rgbString = "R: " + Color.red(color) + " B: " + Color.blue(color) + " G: " + Color.green(color);
                String hexRed = "0x" + Integer.toHexString(Color.red(color));
                String hexGreen = "0x" + Integer.toHexString(Color.green(color));
                String hexBlue= "0x" + Integer.toHexString(Color.blue(color));
                Log.e("hex string", hexRed + hexGreen + hexBlue);

生成的日志是........ 0xb30x120xff

我想要的已经完成了

但我想将其转换为字节,然后将它们作为字节数组加入,这样完全可以正常工作

byte[] hex_txt = {(byte)0xff, (byte)0x00, (byte)0x00};
sendData(hex_txt);

我的问题是如何将这个字符串转换成这样,以便我可以发送数据......

byte byteRed = Byte.valueOf(hexRed);

这不是有效的数字格式异常也尝试了其他无效的解决方案

提前谢谢帮助

【问题讨论】:

  • 当上面给出NumberFormatException 时,hexRed 是什么?
  • java convert to int 的可能重复项
  • valueOf 无法识别 0x。有关一些解决方案,请参阅this answer
  • 数字格式异常发生在我直接使用 hexred 转换时,所以发生这种情况时会出现问题......所以你是对的,但是 byte byteRed = Byte.valueof("ff") 之间有什么区别我发送这个 byteRed 或转换这个 (byte)0xff ?
  • #1:如果你想在十六进制数字字符串上使用valueOf,你需要说Byte.valueOf(yourString, 16)。 #2:Byte 是一个从 -128 到 127 的有符号类型,所以如果你给它"ff" 它仍然会失败,因为它是 255 并且超出了范围。如果您想这样做,请使用Integer.valueOf,然后转换为Byte。 (实际上,您需要先转换为 (int) 以取消对类型的装箱,然后再将其转换为 (byte)。)

标签: java android hex byte


【解决方案1】:

您只能将字符串转换为字节数组,反之亦然。

        String example = "This is an example";
        byte[] bytes = example.getBytes();

        System.out.println("Text : " + example);
        System.out.println("Text [Byte Format] : " + bytes);

谷歌“将字符串转换为字节”,你会发现很多关于将字符串转换为字节[]

http://www.mkyong.com/java/how-do-convert-string-to-byte-in-java/

【讨论】:

  • 问题与转换其中包含十六进制数字的字符串有关。 getBytes 不会那样做。
  • 你能解释一下我问的是什么,因为我需要特定的格式...你的意思是 getbytes 的 0xb30x120xff 字符串可以工作吗?
猜你喜欢
  • 2021-10-31
  • 2019-02-12
  • 2016-05-05
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多