"But if user set 5 0b10000 = hexStr = 10 in command[2] it gets value = 0x0A
.
Why is it changing value?"
It is correct. What different result are you expecting?
For example : If progress
is 5 then...
Doing bit shift like 1 << progress-1
== 1 << 4
= (resulting bits= 0001
0000
) which gives :
int shl = 10
in hex format or even int shl = 16
in decimal format
Doing String hexStr = Integer.toHexString(shl);
puts shl
's "10" hex string value to the other string hexStr
(ie: is also now a "10")...
Doing byte bit = Byte.decode(hexStr)
makes a byte with a decimal value of hexStr
's "10".
This is how your result is command[2]
saying hex value of 0x0A
which == decimal value of 10
.
....
"I'm not translating decimal to binary or hex, but the user input which tells on which position "1" should go. Hope it's clear..."
Why not just write "1" and then add as many zeroes as required (padding)?
Note: I'm not sure what value command[2]=
is supposed to get. Maybe it checks the 8 bits of that byte, or maybe it expects a number (integer). It's confusng becuase your numbers rely on "1 followed by zeroes", also binary can be "1 followed by zeroes"
Binary : There are 8 bits in a byte, so the max binary you can send is 10000000
only.
Integer : A single byte is signed so the max value s 128. By this logic your options are 1
, 10
, 100
only.
See if this helps (check which command[2]=
you want. I've commented //
them out for now) :
int progress = 5;
int shl = 1 << progress-1; //why??
String hexStr = Integer.toHexString(shl);
String shlStr = Integer.toString(shl);
String zeroStr = "";
byte bit = Byte.decode(hexStr);
//command[2]=bit;
System.out.println("shl result string : " + shlStr);
System.out.println("Bytes string hex : " + hexStr);
//# Padding
for(int i = 0; i < (progress-1); i++)
{ zeroStr += "0"; }
shlStr = "1" + zeroStr;
//command[2]= Byte.decode(shlStr);
System.out.println("Result string hex : " + zeroStr);
System.out.println("shi padding string : " + shiStr);