byte[] toString() gives a weird string instead of actual value

♀尐吖头ヾ 提交于 2021-02-02 10:02:00

问题


byte[] a has value of {119}, which is the ascii equivalent of "w", but when I use .toString() to convert it to string, it gives me a weird string. any idea what I did wrong?

simple image description

byte[] a = characteristicRX.getValue();
        String rscvString = a.toString();
        Log.d("byteToHex", "rscvString = " + rscvString);
        while ( rscvString != "w" ){

回答1:


String object takes a parameter of byte[] as an overloaded constructor. Use String rscvString = new String(a); and you should be sorted

You can't use boolean operators to test against strings ie. != or ==. use while ( !(rscvString.equalsIgnoreCase("w") ) the equalsIgnoreCase() method will return a boolean and the ! will force the test against the false.




回答2:


Try one of the lines below to cast a byte to a character and transform it to String

String rscvString = String.valueOf((char) a);
String rscvString = String.valueOf((char) (a & 0xFF));

You can pass a byte array in the String constructor to get a String object of your array.



来源:https://stackoverflow.com/questions/46564310/byte-tostring-gives-a-weird-string-instead-of-actual-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!