Posts

Showing posts with the label Int

Convert Bytes To Int?

Answer : Assuming you're on at least 3.2, there's a built in for this: int.from_bytes ( bytes, byteorder, *, signed=False ) ... The argument bytes must either be a bytes-like object or an iterable producing bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. The signed argument indicates whether two’s complement is used to represent the integer. ## Examples: int.from_bytes(b'\x00\x01', "big") # 1 int.from_bytes(b'\x00\x01', "little") # 256 int.from_bytes(b'\x00\x10', byteorder='little') # 4096 int.from_bytes(b'\xfc...

Convert Unsigned Int To Signed Int C

Answer : It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting. Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases: unsigned int x = 65529; int y = (short) x; // If short is a 16-bit integer. or alternatively: unsigned int x = 65529; int y = (int16_t) x; // This is defined in <stdint.h> I know it's an old question, but it's a good one, so how about this? unsigned short int x = 65529U; short int y = *(short int*)&x; printf("%d\n", y); @Mysticial got it. A short is usually 16-bit and will illustrate the answer: int main() { unsigned int x = 65529; int y = (int) x; printf("%d\n", y); unsigned short z = 65529; short...

Converting String To Int With Swift

Answer : Updated answer for Swift 2.0+ : toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String : let a: Int? = Int(firstTextField.text) let b: Int? = Int(secondTextField.text) Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x): // toInt returns optional that's why we used a:Int? let a:Int? = firstText.text.toInt() // firstText is UITextField let b:Int? = secondText.text.toInt() // secondText is UITextField // check a and b before unwrapping using ! if a && b { var ans = a! + b! answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel } else { answerLabel.text = "Input values are not numeric" } Update for Swift 4 ... let a:Int? = Int(firstText.text) // firstText is UITextField let b:Int? = Int(secondText.text) // secondText is UITextField...