如何在Swift 3中将小数二进制转换为小数?

时间:2017-11-08 08:42:19

标签: swift swift3 binary decimal

我正在寻找一种在Swift 3中将小数二进制部分转换为小数部分的方法。此代码将二进制整数转换为十进制

PS C:\Users\Administrator.DOMAIN> Start-ADSyncSyncCycle -PolicyType Initial
Start-ADSyncSyncCycle :
System.Management.Automation.CmdletInvocationException: System.Exception:
Unexpected exception thrown. Action:
ProvisioningWebServiceAdapter::GetCompanyConfiguration, Exception:  --->
System.Runtime.InteropServices.COMException
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
   at System.Management.ManagementBaseObject.GetPropertyValue(String
propertyName)
   at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomainCont
rollerCore()
   at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainController()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
   at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
awsOperation, String opsLabel)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConfiguration>
b__0()
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   --- End of inner exception stack trace ---
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean
includeLicenseInformation)
   at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudEnforc
edSyncSchedulerInterval()
   at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.get_C
urrentSchedulerSettings()
   at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* ,
_ConfigAttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized,
Char** errorString) ---> System.InvalidOperationException: System.Exception:
Unexpected exception thrown. Action:
ProvisioningWebServiceAdapter::GetCompanyConfiguration, Exception:  --->
System.Runtime.InteropServices.COMException
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
   at System.Management.ManagementBaseObject.GetPropertyValue(String
propertyName)
   at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomainCont
rollerCore()
   at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainController()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
   at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
awsOperation, String opsLabel)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConfiguration>
b__0()
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   --- End of inner exception stack trace ---
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean
includeLicenseInformation)
   at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudEnforc
edSyncSchedulerInterval()
   at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.get_C
urrentSchedulerSettings()
   at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* ,
_ConfigAttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized,
Char** errorString)
   at Microsoft.DirectoryServices.MetadirectoryServices.UI.WebServices.MMSWebSe
rvice.GetSchedulerSettings(String& settingsDeserialized, String& errorString)
   at Microsoft.IdentityManagement.PowerShell.Cmdlet.GetADSyncScheduler.Process
Record()
   --- End of inner exception stack trace ---
   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
   at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork
(Runspace rs, Boolean performSyncInvoke)
   at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndD
oWork(Runspace rsToUse, Boolean isSync)
   at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](
PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings
settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSData
Collection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable
input, PSDataCollection`1 output, PSInvocationSettings settings)
   at Microsoft.Online.Deployment.PowerShell.LocalPowerShell.Invoke()
   at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.TypeDependencies
.InvokePowerShell(IPowerShell powerShell)
   at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.InvokePowerShell
Command(String commandName, InitialSessionState initialSessionState,
IDictionary`2 commandParameters, Boolean isScript)
   at Microsoft.Azure.ActiveDirectory.Synchronization.PowerShellConfigAdapter.S
chedulerPowerShellAdapter.GetCurrentSchedulerSettings()
   at
Microsoft.MetadirectoryServices.Scheduler.Scheduler.StartSyncCycle(String
overridePolicy, Boolean interactiveMode)
   at SchedulerUtils.StartSyncCycle(SchedulerUtils* , Char* policyType, Int32
interactiveMode, Char** errorString)
At line:1 char:1
+ Start-ADSyncSyncCycle -PolicyType Initial
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (Microsoft.Ident...ADSyncSyncCycle:S
   tartADSyncSyncCycle) [Start-ADSyncSyncCycle], InvalidOperationException
    + FullyQualifiedErrorId : System.Management.Automation.CmdletInvocationExc
   eption: System.Exception: Unexpected exception thrown. Action: Provisionin
  gWebServiceAdapter::GetCompanyConfiguration, Exception:  ---> System.Runti
 me.InteropServices.COMException
       at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(I
   nt32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
       at System.Management.ManagementBaseObject.GetPropertyValue(String prope
   rtyName)
       at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomai
   nControllerCore()
       at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainControll
   er()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
       at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
   awsOperation, String opsLabel)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConf
  iguration>b__0()
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
   --- End of inner exception stack trace ---
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean in
  cludeLicenseInformation)
       at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudE
   nforcedSyncSchedulerInterval()
       at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.
   get_CurrentSchedulerSettings()
       at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* , _Config
   AttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized, Char*
  * errorString) ---> System.InvalidOperationException: System.Exception: Un
 expected exception thrown. Action: ProvisioningWebServiceAdapter::GetCompa
nyConfiguration, Exception:  ---> System.Runtime.InteropServices.COMExcept
ion
       at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(I
   nt32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
       at System.Management.ManagementBaseObject.GetPropertyValue(String prope
   rtyName)
       at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomai
   nControllerCore()
       at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainControll
   er()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
       at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
   awsOperation, String opsLabel)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConf
  iguration>b__0()
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
   --- End of inner exception stack trace ---
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean in
  cludeLicenseInformation)
       at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudE
   nforcedSyncSchedulerInterval()
       at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.
   get_CurrentSchedulerSettings()
       at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* , _Config
   AttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized, Char*
  * errorString)
       at Microsoft.DirectoryServices.MetadirectoryServices.UI.WebServices.MMS
   WebService.GetSchedulerSettings(String& settingsDeserialized, String& erro
  rString)
       at Microsoft.IdentityManagement.PowerShell.Cmdlet.GetADSyncScheduler.Pr
   ocessRecord()
   --- End of inner exception stack trace ---
       at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerab
   le input)
       at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndD
   oWork(Runspace rs, Boolean performSyncInvoke)
       at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeede
   dAndDoWork(Runspace rsToUse, Boolean isSync)
       at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOut
   put](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSett
  ings settings)
       at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](P
   SDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings s
  ettings)
       at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumera
   ble input, PSDataCollection`1 output, PSInvocationSettings settings)
   at Microsoft.Online.Deployment.PowerShell.LocalPowerShell.Invoke()
       at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.TypeDepende
   ncies.InvokePowerShell(IPowerShell powerShell)
       at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.InvokePower
   ShellCommand(String commandName, InitialSessionState initialSessionState,
  IDictionary`2 commandParameters, Boolean isScript)
       at Microsoft.Azure.ActiveDirectory.Synchronization.PowerShellConfigAdap
   ter.SchedulerPowerShellAdapter.GetCurrentSchedulerSettings()
       at Microsoft.MetadirectoryServices.Scheduler.Scheduler.StartSyncCycle(S
   tring overridePolicy, Boolean interactiveMode)
       at SchedulerUtils.StartSyncCycle(SchedulerUtils* , Char* policyType, In
   t32 interactiveMode, Char** errorString),Microsoft.IdentityManagement.Powe
  rShell.Cmdlet.StartADSyncSyncCycle

PS C:\Users\Administrator.DOMAIN>

也许有相同的解决方法但仅适用于小数部分?

例如: 101.0101至5.3125(十进制)

1 个答案:

答案 0 :(得分:3)

一旦遇到小数点,就必须切换 为结果增加1/2的权力:

func fractionalBinaryToDecimal(bin: String) -> Double? {
    var result = 0.0
    var inFractionalPart = false // Set to `true` if the decimal point is encountered
    var fractionalValue = 1.0 // Current power of 1/2 when adding the fractional part

    for digit in bin.characters { // Swift 4: for digit in bin { ...
        switch digit {
        case "0":
            if inFractionalPart {
                fractionalValue /= 2.0
            } else {
                result = 2 * result
            }
        case "1":
            if inFractionalPart {
                fractionalValue /= 2.0
                result += fractionalValue
            } else {
                result = 2 * result + 1
            }
        case ".":
            guard !inFractionalPart else { return nil } // Repeated decimal point
            inFractionalPart = true
        default:
            return nil // Invalid digit
        }
    }

    return result
}

示例:

if let val = fractionalBinaryToDecimal(bin: "101.0101") {
    print(val) // 5.3125
}