Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save krzyzanowskim/bc6ee103c76266b69880 to your computer and use it in GitHub Desktop.

Select an option

Save krzyzanowskim/bc6ee103c76266b69880 to your computer and use it in GitHub Desktop.
Calculate number of bits for Big Integer
// 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