从二进制快速字符串中获取有符号整数 [英] Get signed integer from swift string of binary

查看:94
本文介绍了从二进制快速字符串中获取有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试使用功能

I'm currently trying to use the function

Int(binaryString, radix: 2)

将二进制字符串转换为Int.但是,此函数似乎总是将二进制字符串转换为无符号整数.例如

to convert a string of binary to an Int. However, this function seems to always be converting the binary string into an unsigned integer. For example,

Int("1111111110011100", radix: 2)

如果它正在执行带符号的int转换,则我期望从它获得-100时返回65436.我并没有真正使用二进制文件,所以我想知道我应该在这里做什么? Swift3内建有一种代码有效的方式来对带符号的int做到这一点吗?我最初希望它能工作,因为它是一个Int构造函数(不是UInt).

returns 65436 when I'd expect to get -100 from it if it were doing an signed int conversion. I haven't really worked with binary much, so I was wondering what I should do here? Is there a code-efficient way built-into Swift3 that does this for signed ints? I had initially expected this to work because it's an Int constructor (not UInt).

推荐答案

在游戏中玩耍可以得到所需的结果,如下所示:

Playing around you can get the desired result as follows:

let binaryString = "1111111110011100"
print(Int(binaryString, radix: 2)!)
print(UInt16(binaryString, radix: 2)!)
print(Int16(bitPattern: UInt16(binaryString, radix: 2)!))

输出:

65436
65436
-100

65436
65436
-100

所需的结果来自使用UInt16的位模式创建带符号的Int16.

The desired result comes from creating a signed Int16 using the bit pattern of a UInt16.

这篇关于从二进制快速字符串中获取有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆