Long to hexString , wrong size - android

I work with my custom USB Device. I get from it bytes array. I want to display this array as hex string so I convert it firstly into Long like this :
byte[] receivedTag = connector.receive(512);
String tag = null;
if (receivedTag != null) {
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
Next I want to convert it into hex String :
tag = Long.toHexString(tagValue);
however I've got problem here. Received Tag has something about 400 bytes (I've checked it on debug) , but when I convert it , tag is only 16 chars long(8 bytes, there are correct). Why is that ?

public static String bytesToHex(byte[] in) {
final StringBuilder builder = new StringBuilder();
for(byte b : in) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
// consider using this

Related

How to convert emoji unicode in android

In anroid emoji convert to unicode time alwasy get output U+5c but we give emoji string "\uD83D\uDE21" this method it's working
String a = emojiconEditText.getText().toString().trim();
String text = new String(
StringEscapeUtils.escapeJava(a).getBytes(),
StandardCharsets.UTF_8
);
int codepoint = text.codePointAt(0);
String yourUnicode = "U+"+Integer.toHexString(codepoint);
You can encode/decode emojis to the following unicode UTF-8, UTF-16 and U+<hex> using the below:
try {
//I am assuming you are getting unicode from an inputbox
String emoji = emojiconEditText.getText().toString().trim();
//I am also assuming you are getting emoji in hexadecimal form `U+<hexdigits>`
String unicodeHexEmoji = "U+";
StringBuilder sb = new StringBuilder();
//Firstly you want to encode emojis to unicode types by converting to byte array
byte[] utf8Bytes = emoji.getBytes("UTF-8"); // "\\uf0\\u9f\\u98\\u80"
byte[] utf16Bytes = emoji.getBytes("UTF-16"); // "\\ud83d\\ude00"
//convert emoji to hex
for (byte b : utf16Bytes ) {
sb.append(String.format("%02x", b));
}
//we are converting our current emoji to hex just for the purpose of this example
unicodeHexEmoji += sb; //yields "U+feffd83dde21";
byte[] utfHexBytes = getByteFromHex(unicodeHexEmoji.replace("U+","")); // "\\ud83d\\ude00"
//NB: we removed "U+" because its only a prefix denoting that the string is a <hex>
//Decoding our unicodes back to emoji string
String emojiUTF_8 = new String(utf8Bytes,"UTF-8");
String emojiUTF_16 = new String(utf16Bytes,"UTF-16");
String emojiUTF_hex = new String(utfHexBytes,"UTF-16");
Log.d("Tag", "emojiUTF_8 : "+ emojiUTF_8);
Log.d("Tag", "emojiUTF_16 : "+ emojiUTF_16)
Log.d("Tag", "emojiUTF_hex : "+ emojiUTF_hex)
//output
//emojiUTF-8 : 😀
//emojiUTF-16 : 😀
//emojiUTF-hex : 😡
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
...
public byte[] getByteFromHex(String hexString){
//To convert hex string to byte array, you need to first get the length
//of the given string and include it while creating a new byte array.
byte[] val = new byte[hexString.length() / 2];
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(hexString.substring(index, index + 2), 16);
val[i] = (byte) j;
}
return val;
}

How to assign StringBuilder to String value at Android?

I have a dynamic message Stringbuilder value in my codes.
But i want to create temp string and i want to save message value to temp value and than clean message value:
For example:
StringBuilder messages;
StringBuilder [] temp = new StringBuilder[1000];
...///other part of codes
temp[i]=message;
String text=intent.getStringExtra("theMessage");
i++;
messages.delete(0, messages.length());
A mean, when my messages come 34 i want to save temp[0] and clean message and i want to increase i with i++ and than message come 23 than temp[1]=23 and so on... How can i do this at android ?
Its as simple as following:
StringBuilder [] temp = new StringBuilder[1000];
int index = 0;
if(messages.length() == 34){
temp[index] = new StringBuilder(messages);
messages.delete(0, messages.length());
}
...
If temp[] is of type String then simply
temp[index] = new StringBuilder(messages.toString())

HMAC SHA1 android with input string and input key is Hex String

this is my first post! So if anything is wrong please tell me, i am new to android developing! Here is my question:
I am trying to generate HMAC-SHA1 with input is Hexstring for example the input key is "2cb1b780138bc273459232edda0e4b96" and input value is HexString too but way longer than the key, all the value and the key are Hexstring not character or normal string, so how can i achieve this? I searched a lot but all the result came to use the value and the key in normal string like "The quick brown fox jumps over the lazy dog"
I tried using convertHextoString code to change my HexString into Character string and put in the function like you did but the converted String from convertHextoString appear to have many SPECIAL CHARACTERS such as "\n" or ":" or "%" and so on and i think that is the problem why i got the wrong output. Here is my convertHextoString function
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
and the function to HMAC:
static String hash_hmac(String type, String value, String key) {
try { Log.i("Hien - value - hmac",value);
javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
mac.init(secret);
byte[] digest = mac.doFinal(value.getBytes());
StringBuilder sb = new StringBuilder(digest.length*2);
String s;
for (byte b : digest){
s = Integer.toHexString(b & 0xff);
if(s.length() == 1) sb.append('0');
sb.append(s);
}
return sb.toString();} catch (Exception e) { android.util.Log.v("TAG","Exception ["+e.getMessage()+"]", e); } return ""; }
Please help!

getBytes doesn't get the right bytes amount

I need to create a string of hex values. Now, i've got something like this.
String address = "5a f2 ff 1f";
But when getting this address into bytes:
byte[] bytes= address.getBytes();
It gets me each letter and space as a byte, instead of getting each 2 chars as a byte ang leaving the spaces. So...
How can i declare this?
private String CalcChecksum (String message) {
/**Get string's bytes*/
message = message.replaceAll("\\s","");
byte[] bytes = toByteArray(message);
byte b_checksum = 0;
for (int byte_index = 0; byte_index < byte_calc.length; byte_index++) {
b_checksum += byte_calc[byte_index];
}
int d_checksum = b_checksum; //Convert byte to int(2 byte)
int c2_checksum = 256 - d_checksum;
String hexString = Integer.toHexString(c2_checksum);
return hexString;
}
String address = "5a f2 ff 1f";
byte[] bytes = DatatypeConverter.parseHexBinary(address.replaceAll("\\s","")).getBytes();
As stated you're using hex, which you cannot use .getBytes() in the way you are trying to!
You need to specify that your string contains hex values. And in the solution below you need to remove all whitespaces from the string before converting it:
import javax.xml.bind.DatatypeConverter;
class HexStringToByteArray {
public static void main(String[] args) {
String address = "5A F2 FF 1F";
address = address.replaceAll("\\s","");
System.out.println(address);
byte[] bytes = toByteArray(address);
for( byte b: bytes ) {
System.out.println(b);
}
String string_again = toHexString(bytes);
System.out.println(string_again);
}
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
}
This will print (note that bytes as signed):
5AF2FF1F // Original address
90 // 5A
-14 // F2
-1 // FF
31 // 1F
5AF2FF1F // address retrieved from byte array

Convert Hex to Binary at android

I used this code for converts hex to binary but works only with 8 bits.How can i expand to 16bits?For example i want to convert FFFF to 1111111111111111 ....also i need to fill the zero 0...
void HexToBinary1(String Hex) {
int i = Integer.parseInt(Hex, 16);//16 bits
String Bin = Integer.toBinaryString(i);//Converts int to binary
String Bin2="";
if(Bin.length()==8){Bin2=Bin;}
if(Bin.length()==7){Bin2="0"+Bin;}
if(Bin.length()==6){Bin2="00"+Bin;}
if(Bin.length()==5){Bin2="000"+Bin;}
if(Bin.length()==4){Bin2="0000"+Bin;}
if(Bin.length()==3){Bin2="00000"+Bin;}
if(Bin.length()==2){Bin2="000000"+Bin;}
if(Bin.length()==1){Bin2="0000000"+Bin;}
text1.setText(Bin2);//Shows binary
}
use
String HexToBinary(String Hex) {
String bin = new BigInteger(Hex, 16).toString(2);
int inb = Integer.parseInt(bin);
bin = String.format(Locale.getDefault(),"%08d", inb);
return bin;
}
It will return binary string as 8 digit format.
you need to tell Java that the int is in hex, like this:
String HexToBinary(String Hex) {
int i = Integer.parseInt(Hex, 16);
String Bin = Integer.toBinaryString(i);
return Bin;
}
Try this
public static String getBits(double value)
{
//get bit-string of double
String printString = (Long.toBinaryString(Double.doubleToRawLongBits(value)));
//add leading zeros if bitstring is shorter than 64 bits
while (printString.length() < 64)
printString = "0" + printString;
//format string by adding byte padding
StringBuilder bitwise = new StringBuilder();
for(int i = 0; i<8; i++)
bitwise.append(printString.substring(i*8, (i+1)*8)+" ");
return bitwise.toString();
}
Feel free to further adapt for ints and add in the feature of parsing a HEX string.

Categories

Resources