HarmonyOS NEXT 进制转换方案分享

2025-03-19 20:44:39
142次阅读
0个评论
最后修改时间:2025-03-19 20:47:27

【功能概述】 本案例实现了一个多进制转换工具,支持十进制与二进制、八进制、十六进制之间的相互转换。通过ArkUI框架构建直观的界面,结合自定义工具类实现高效数值计算,并利用状态管理实现实时结果

【实现效果】

GIF 2025-3-17 10-30-05.gif

【环境准备】 • 操作系统:Windows 10 • 开发工具:DevEco Studio(5.0.7.210) • 目标设备:华为Mate60 Pro • 开发语言:ArkTS • 框架:ArkUI • API版本:API 14

【工程目录】

│  ├─ hvigorfile.ts
│  ├─ obfuscation-rules.txt
│  ├─ oh-package.json5                   //声明依赖
│  └─ src
│     ├─ main
│     │  ├─ ets
│     │  │  ├─ entryability
│     │  │  │  └─ EntryAbility.ets        //程序入口类
│     │  │  ├─ entrybackupability
│     │  │  │  └─ EntryBackupAbility.ets
│     │  │  └─ pages
│     │  │     └─ Index.ets              //主页入口
│     │  ├─ module.json5                 //模块配置相关
│     │  └─ resources                    //应用静态资源
│     │     ├─ base
│     │     │  ├─ element
│     │     │  │  ├─ color.json
│     │     │  │  ├─ float.json
│     │     │  │  └─ string.json
│     │     │  ├─ media
│     │     │  │  ├─ background.png
│     │     │  │  ├─ foreground.png
│     │     │  │  ├─ layered_image.json
│     │     │  │  └─ startIcon.png
│     │     │  └─ profile
│     │     │     ├─ backup_config.json
│     │     │     └─ main_pages.json
│     │     ├─ dark
│     │     │  └─ element
│     │     │     └─ color.json
│     │     └─ rawfile

【具体实现】

  1. 进制转换算法封装
public decimalToBinaryUtil(decimal: number): string {
  while (decimal > 0) {
    binary = (decimal % 2) + binary; // 取余逆序拼接
    decimal = Math.floor(decimal / 2);
  }
}

// 二进制转十进制(位权展开法)
public binaryToDecimalUtil(binary: string): number {
  for (let i = binary.length - 1; i >= 0; i--) {
    if (binary[i] === '1') {
      decimal += base; // 累加位权值
    }
    base *= 2; // 位权递增
  }
}

特点: ● 实现6种进制转换算法(十↔二/八/十六) ● 算法时间复杂度均为O(n),适合移动端轻量化计算 ● 通过工具类隔离业务逻辑与UI层

  1. UI设计与交互逻辑
  Column() {
    // 输入区域
    TextInput({ text: this.text })
      .onChange((value: string) => {
        this.text = value // 实时绑定输入
      })
    
    // 结果显示
    Text(`结果为:${this.text3}`)
      .backgroundColor('#ededed')
    
    // 功能按钮组
    Row({ space: 10 }) {
      Button('十转二').onClick(() => {
        this.text3 = this.ToBinary()
        promptAction.showToast(...) // 弹窗反馈
      })
      // 其他按钮...
    }
  }
}

界面特征: ● 采用Column+Row实现流式布局 ● 输入框与结果区域通过.backgroundColor('#ededed')突出显示 ● 按钮组采用橙色系配色(#ee8848),提升视觉识别度 ● 通过promptAction.showToast提供即时操作反馈

【状态管理与数据流】

  1. 状态声明

@State text: string = '' // 输入文本 @State text3: string = '' // 转换结果 @State text4: string = '' // 原始输入备份

  1. 数据流转逻辑

用户输入 → TextInput.onChange → 更新this.text ↓ 按钮点击 → 调用转换工具类 → 结果写入this.text3 ↓ 界面自动刷新 → 显示this.text3 关键设计: ● 使用@State装饰器实现双向数据绑定 ● 通过text4保留原始输入,确保多次转换时数据一致性 ● 转换方法返回字符串直接更新状态变量 完整代码:

import { promptAction } from '@kit.ArkUI'
/**
 *十进制转二进制
 * @param decimal十进制数
 * @returns二进制数
 */
class DecimalToBinaryUtil {
  public decimalToBinaryUtil(decimal: number): string {
    if (decimal <= 0) {
      return '';
    }
    let binary = '';
    while (decimal > 0) {
      binary = (decimal % 2) + binary;
      decimal = Math.floor(decimal / 2);
    }
    return binary;
  }
}

/*
二进制转十进制
 */
export class BinaryToDecimalUtil {
  public binaryToDecimalUtil(binary: string): number {
    let decimal: number = 0;
    let base: number = 1;
    for (let i: number = binary.length - 1; i >= 0; i--) {
      if (binary[i] === '1') {
        decimal += base;
      }
      base *= 2;
    }
    return decimal;
  }
}

/*
十进制转十六进制
 */
export class DecimalToHexadecimallUtil {
  public decimalToHexadecimallUtil(decimal: number): string {
    let hex = '';
    while (decimal > 0) {
      let digit = decimal % 16;
      //hex = (digit > 9 ?'':'0') + digit.toString(16) + hex;
      hex = digit.toString(16) + hex;
      decimal = Math.floor(decimal / 16);
    }
    return hex;
  }
}

/**
 *十六进制转十进制
 * @param hex hex string
 * @returns number
 */
export class HexadecimalToDecimalUtil {
  public hexadecimalToDecimalUtil(hex: string): number {
    return parseInt(hex, 16);
  }
}

/*
十进制转八进制
 */
export class DecimalToOctalUtil {
  public decimalToOctalUtil(num: number): string {
    if (num === 0) {
      return '0';
    }
    let octal = '';
    while (num > 0) {
      octal = (num % 8) + octal;
      num = Math.floor(num / 8);
    }
    return octal;
  }
}

/*
八进制转十进制
 */
export class OctalToDecimalUtil {
  public octalToDecimalUtil(octal: string): number {
    let decimal = 0;
    let base = 0;
    while (octal.length > 0) {
      decimal += Math.floor(Number(octal[octal.length - 1])) * Math.pow(8, base);
      base++;
      octal = octal.substring(0, octal.length - 1);
    }
    return decimal;
  }
}


@Entry
@Component
export default struct Decimal {
  @State
  text: string = ''
  @State
  text3: string = ''
  @State
  text4: string = ''
  //十进制转二进制
  decimalToBinary = new DecimalToBinaryUtil()

  ToBinary() {
    let num: number = 0
    num = Number(this.text)
    const N1 = this.decimalToBinary.decimalToBinaryUtil(num)
    this.text = N1
    return this.text
  }

  //十进制转八进制
  DecimalToOctal = new DecimalToOctalUtil()

  ToOctal() {
    let num: number = 0
    num = Number(this.text)
    const N1 = this.DecimalToOctal.decimalToOctalUtil(num)
    this.text = N1
    return this.text
  }

  //十进制转十六进制
  decimalToHexadecimall = new DecimalToHexadecimallUtil()

  ToHexadecimal() {
    let num: number = 0
    num = Number(this.text)
    const N1 = this.decimalToHexadecimall.decimalToHexadecimallUtil(num)
    this.text = N1
    return this.text
  }

  //二进制转十进制
  binaryToDecimal = new BinaryToDecimalUtil()

  binaryToDecimalUtil() {
    const N1 = this.binaryToDecimal.binaryToDecimalUtil(this.text)
    this.text = N1.toString()
    return this.text
  }

  //八进制转十进制
  octalToDecimal = new OctalToDecimalUtil()

  octalToDecimalUtil() {
    const N1 = this.octalToDecimal.octalToDecimalUtil(this.text)
    this.text = N1.toString()
    return this.text
  }

  //十六进制转十进制
  hexadecimalToDecimal = new HexadecimalToDecimalUtil()

  hexadecimalToDecimalUtil() {
    const N1 = this.hexadecimalToDecimal.hexadecimalToDecimalUtil(this.text)
    this.text = N1.toString()
    return this.text
  }

  //**
  @State daysToCollegeEntranceExamination: number = 0 //距离高考时间
  private selectedGaokaoDate: Date = new Date() // 选定的高考日期
  private selectedShedingDate: Date = new Date() // 选定的当前日期

  private X1(): number {
    let data1 = new Date(this.selectedShedingDate); // 将选中的第一个日期字符串转换为Date对象
    let data2 = new Date(this.selectedGaokaoDate); // 将选中的第二个日期字符串转换为Date对象
    let timeDiff = Math.abs(data2.getTime() - data1.getTime()); // 计算时间差
    this.daysToCollegeEntranceExamination = Math.ceil(timeDiff / (1000 * 3600 * 24)); // 转换为天数
    return this.daysToCollegeEntranceExamination
  }

  build() {
    Column() {
      Text('进制转换')
        .margin({ top: 12, bottom: 6 })
        .fontWeight(FontWeight.Bold)
        .fontSize(30)

      Divider()
        .width(300)
        .margin({ top: 10 })

      Column({ space: 8 }) {
        TextInput({ text: this.text, placeholder: '输入转换的数字......', })
          .type(InputType.Normal)
          .width('95%')
          .height(50)
          .fontSize(15)
          .backgroundColor('#ededed')
          .onChange((value: string) => {
            this.text = value
            this.text4 = this.text
          })
        Text(`    结果为:${this.text3}`)
          .width('95%')
          .height(50)
          .fontSize(15)
          .fontWeight(FontWeight.Bold)
          .backgroundColor('#ededed')
          .borderRadius(20)
          .margin({ top: 10 })
        Row({ space: 10 }) {
          Button('十转二')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.ToBinary()
              this.text = this.text4
              promptAction.showToast({ message: `【十进制转二进制】结果为:${this.text3}` })
            })
          Button('十转八')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.ToOctal()
              this.text = this.text4
              promptAction.showToast({ message: `【十进制转八进制】结果为:${this.text3}` })
            })
        }
        .justifyContent(FlexAlign.Center)
        .width('100%')
        .margin({ top: 10 })

        Row({ space: 10 }) {
          Button('八转十')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.octalToDecimalUtil()
              this.text = this.text4
              promptAction.showToast({ message: `【八进制转十进制】结果为:${this.text3}` })
            })
          Button('二转十')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.binaryToDecimalUtil()
              this.text = this.text4
              promptAction.showToast({ message: `【二进制转十进制】结果为:${this.text3}` })
            })
        }
        .justifyContent(FlexAlign.Center)
        .width('100%')

        Row({ space: 10 }) {
          Button('十转十六')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.ToHexadecimal()
              this.text = this.text4
              promptAction.showToast({ message: `【十进制转十六进制】结果为:${this.text3}` })
            })

          Button('十六转十')
            .width(160)
            .height(50)
            .backgroundColor('#ee8848')
            .fontColor('#393939')
            .backgroundColor(Color.Orange)
            .onClick(() => {
              this.text3 = this.hexadecimalToDecimalUtil()
              this.text = this.text4
              promptAction.showToast({ message: `【十六进制转十进制】结果为:${this.text3}` })
            })
        }
        .justifyContent(FlexAlign.Center)
        .width('100%')

      }
      .borderRadius(20)
      .width('100%')
      .height('100%')

    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.White)
    .borderRadius(20)
  }
}
收藏00

登录 后评论。没有帐号? 注册 一个。