HarmonyOS鸿蒙Next中Integer如何转成byte?

HarmonyOS鸿蒙Next中Integer如何转成byte?

(java版)  
(byte) Integer.valueOf("C2", 16);
获得的值是-62  

那么etc该如何写呢?目前是这样  
parseInt("C2", 16)
获得的值是没有转成byte之前的:194  

我用另一个方法也是如此:  
static hexString2Bytes(hexString: string): Uint8Array {
  let len = hexString.length

  if (len % 2 != 0) {
    hexString = "0" + hexString
  }
  const byteArray = new Array<number>()
  for (let i = 0; i < hexString.length; i += 2) {
    byteArray.push(parseInt(hexString.substring(i, i + 2), 16))
  }
  return new Uint8Array(byteArray)
}

更多关于HarmonyOS鸿蒙Next中Integer如何转成byte?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复
@Entry
@Component
struct Test {
  build() {
    Column() {
      Button('测试')
        .width('300lpx')
        .height('300lpx')
        .onClick(() => {
          function toSignedByte(hexString: string): number {
            const unsignedByte = parseInt(hexString, 16);

            // 模拟Java中8位有符号整数的转换
            const signedByte = ((unsignedByte << 24) >> 24);
            return signedByte;
          }

          const signedByteValue = toSignedByte("C2");
          console.log('signedByteValue', signedByteValue); // signedByteValue -62
        })
    }
    .width('100%')
    .height('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中Integer如何转成byte?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,将Integer类型转换为byte类型可以通过直接类型转换实现。由于Integer是32位有符号整数,而byte是8位有符号整数,转换时需要注意数据溢出的问题。

你可以使用以下代码进行转换:

let intValue: number = 255; // 假设这是一个Integer值
let byteValue: number = intValue & 0xFF; // 转换为byte类型

在这个例子中,intValue & 0xFF操作确保了只保留intValue的低8位,从而将其转换为byte类型。如果intValue的值超出了byte的范围(-128到127),结果将会是截断后的值。

例如,如果intValue为256,转换后的byteValue将为0,因为256的二进制表示是100000000,低8位为00000000

这种转换方式适用于需要将Integer值限制在byte范围内的场景。

在HarmonyOS鸿蒙Next中,将Integer转换为byte可以通过类型强制转换实现。例如:

int intValue = 128;
byte byteValue = (byte) intValue;

注意,由于byte范围是-128到127,若int值超出此范围,转换后会发生数据截断。

回到顶部