1

The binary representation of number 53 is 0b00110101 and -53 is 11001010.

I used 1's complement of 53 to get the binary value of -53.

But when i try to print those binary number as

print(0b00110101) //53
print(0b11001010) //-53

I get the following output.

53

202

How can i make the compiler return the negative representation of the binary value?

3
  • 1
    Note that the (8-bit) 2's complement of 00110101 is 11001011, not 11001010. Commented Jul 5, 2017 at 17:42
  • (you're using 1's complement; not 2's complement) Commented Jul 5, 2017 at 17:44
  • oh yes..Thanks for the slip Commented Jul 5, 2017 at 17:46

1 Answer 1

4

0b11001010 is an integer literal and in print(0b11001010) its type is Int and the value is 202.

But you can create a signed 8-bit value with the same bit pattern:

let x = Int8(bitPattern: 0b11001010)
// Equivalent to:
// let x = Int8(bitPattern: 202)
print(x) // -54

using the Int8(bitPattern:) initializer:

Creates a new instance with the same memory representation as the given value.

(Here the compiler infers the type of the integer literal as UInt8.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..but my head started spinning now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.