Merge pull request #15649 from anujgaud/convert-byte-2-int

[BAEL-7462] Convert byte to int
This commit is contained in:
Maiklins 2024-01-18 22:13:11 +01:00 committed by GitHub
commit 359cdeb004
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package com.baeldung.bytetoint;
public class ByteToIntConversion {
static int usingTypeCasting(byte b){
int i = b;
return i;
}
static int usingIntegerValueOf(byte b){
return Integer.valueOf(b);
}
static int usingByteIntValue(byte b){
Byte byteObj = new Byte(b);
return byteObj.intValue();
}
static int usingMathToIntExact(byte b){
return Math.toIntExact(b);
}
static int usingByteUnsignedInt(byte b){
return Byte.toUnsignedInt(b);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.bytetoint;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ByteToIntConversionUnitTest {
@Test
public void givenByte_whenUsingTypeCasting_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingTypeCasting(b);
assertEquals(-51, result);
}
@Test
void givenByte_whenUsingIntegerValueOf_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingIntegerValueOf(b);
assertEquals(-51, result);
}
@Test
void givenByte_whenUsingByteIntValue_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingByteIntValue(b);
assertEquals(-51, result);
}
@Test
void givenByte_whenUsingMathToIntExact_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingMathToIntExact(b);
assertEquals(-51, result);
}
@Test
void givenByte_whenUsingByteUnsignedInt_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingByteUnsignedInt(b);
assertEquals(205, result);
}
}