iOS 16 进制与 10进制之间的 互转

最近自己也在做蓝牙开发,发现好多做蓝牙开发的都没有接触过C ,字节转换更是晕乎乎的,所以写下此篇博客,提供我转换的方法。

一、整形装换成两个字节

    

    int value = 456;

    unsigned char  byte1 = (value & 0xff00)>>8; //8

    unsigned char  byte2 = (value & 0xff);//8

    

    NSLog(@"byte1= %x   byte2= %x ",byte1,byte2);

  

        byte1 = 1;  byte2= c8;

二、两个字节转换成十进制整数

    char bytes[]={byte1,byte2};

    unsigned char  by1 = (bytes[0] & 0xff); //8

    unsigned char  by2 = (bytes[1] & 0xff);//8

    int   temp  = (by2|(by1<<8));

    NSLog(@"temp = %d",temp);

    

    temp = 456;

三、整形装换成三个字节

    int value =134456;

    unsigned char  byte1 = (value & 0xff0000)>>16;//最高8

    unsigned char  byte2 = (value & 0xff00)>>8;//中间8

    unsigned char  byte3 = (value & 0xff);//8

    

    NSLog(@"byte1= %x   byte2= %x byte3= %x ",byte1,byte2,byte3);

    byte1= 2   byte2= d byte3= 38


四、三个字节转换成十进制整数

    char bytes[]={byte1,byte2,byte3};

    unsigned char  by1 = (bytes[0] & 0xff); //8

    unsigned char  by2 = (bytes[1] & 0xff);//8

    unsigned char  by3 = (bytes[2] & 0xff);//8

    

    int   temp  = (by3|(by2<<8)|(by1<<16));

    NSLog(@"temp = %d",temp);

   temp = 134456

如果还有更多的自己接需要转换以此类推


在Swift语言中,将16进制字符串转换为ASCII码表示的字符串可以通过一系列步骤完成。以下是一个基本的转换过程,它涉及到了将16进制字符串分割成每两个字符一组(因为一个ASCII字符由两个16进制数字表示),然后将每组16进制字符转换为相应的数字,最后将这些数字转换为ASCII字符。 这里是一个简单的Swift函数示例,它实现了上述功能: ```swift func hexToString(_ hex: String) -> String? { guard hex.count % 2 == 0 else { return nil } // 确保16进制字符串长度是偶数 let chars = Array(hex) var result = "" for i in stride(from: 0, to: chars.count, by: 2) { guard let first = CharacterSet.decimalDigits.value.index(of: chars[i]), let second = CharacterSet.decimalDigits.value.index(of: chars[i + 1]) else { return nil } let firstNumber = Int(String([chars[i]])) ?? 0 let secondNumber = Int(String([chars[i + 1]])) ?? 0 let decimalValue = firstNumber * 16 + secondNumber if decimalValue >= 32 && decimalValue <= 126 { // 确保字符在可打印ASCII范围内 result.append(UnicodeScalar(decimalValue)!) } else { return nil } } return result } // 使用示例 let hexString = "48656C6C6F" // 这是"Hello"的16进制表示 if let asciiString = hexToString(hexString) { print("转换后的ASCII字符串: \(asciiString)") // 应该输出"Hello" } else { print("转换失败") } ``` 这个函数首先检查输入的16进制字符串是否为偶数长度,然后通过循环每两个字符分割字符串,并将每两个字符转换为一个ASCII字符,最后将这些字符连接成一个字符串。在转换过程中,它还确保了只转换可打印的ASCII字符范围(32到126)。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值