Last active
August 29, 2015 14:14
-
-
Save krzyzanowskim/bc6ee103c76266b69880 to your computer and use it in GitHub Desktop.
Calculate number of bits for Big Integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Playground - noun: a place where people can play | |
| import Foundation | |
| func numberOfBits(bytes:[Byte]) -> Int { | |
| if (bytes.count == 0) { | |
| return 0; | |
| } | |
| var toRemove = 0; | |
| for (toRemove = 0; toRemove < bytes.count; toRemove++) { | |
| if (bytes[toRemove] != 0x00) { | |
| break; | |
| } | |
| } | |
| // find most significant bit index | |
| var bitIdx = 0; | |
| let first = bytes[toRemove] | |
| var value = first | |
| while (value != 0) { | |
| bitIdx++ | |
| value = value >> 1; | |
| } | |
| return bitIdx + ((bytes.count - toRemove - 1) * 8) | |
| } | |
| let bigIntegerBytes:[Byte] = [0x01,0x00,0x01] | |
| numberOfBits(bigIntegerBytes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment