Reputation: 380
I have two bytes, byte b1
, byte b2
.
b1
decimal value is 44.
b2
decimal value is 1.
I would like to join the bytes together (but not sum), to create a number like 441.
How do I achieve that?
Upvotes: 1
Views: 1109
Reputation: 1254
Mathematical approach
double digitCount = Math.floor(Math.log10(b2) + 1.0);
int result = b1 * (int) Math.pow(10, digitCount) + b2;
Iterative approach (slice one digit at a time from right to left)
int result = 0;
int digit, multiplier = 1;
int base = b2;
while (base > 0) {
digit = base % 10;
base /= 10;
result += digit * multiplier;
multiplier *= 10;
}
base = b1;
while (base > 0) {
digit = base % 10;
base /= 10;
result += digit * multiplier;
multiplier *= 10;
}
Straightforward approach (concatenate as strings and parse)
int result = Integer.parseInt("" + b1 + b2);
Upvotes: 4
Reputation: 121
You could convert them to strings, then concatenate the strings, and then parse it to an int:
Integer.parseInt(Byte.toString(b1) + Byte.toString(b2))
Upvotes: 2
Reputation: 742
Kotlin:
val b1: Byte = 44.toByte()
val b2: Byte = 1.toByte()
print("$b1$b2")
Java
byte b1 = (byte)44;
byte b2 = (byte)1;
System.out.print(b1+""+b2);
Upvotes: 0