-1

In my application I am trying to convert Data to Int 16 but I must be doing something wrong. Here is an example of my problem

let x = "0000001110000111"

if let number = Int(x, radix: 2) {
    
    print(number) // This give 903 which is what I would expect 
    
}

let y = Data(x.utf8)

let convertedData = y.withUnsafeBytes {pointer in
    
    return pointer.load(as: Int16.self)
    
}

print (convertedData) // This gives 12336 which is not what I was expecting

let str = String(decoding: y, as: UTF8.self)

print (str) // I wanted to check and make sure I got the correct binary back
            // This gives 0000001110000111 as I would expect 

What am I doing wrong here?

kka41
  • 69
  • 7
  • What's the purpose of your Data dance? That's not how to turn a string to data and back. – matt Feb 23 '22 at 02:24
  • In the actual application I don't do this dance I simply used this for an example. In my application I have a variable that is Data with 2 bytes that is this exact binary. The problem is I am trying to convert that binary to Int16 and it is not converting properly. In order to figure out what I was doing wrong I made this as an example in a Playground. – kka41 Feb 23 '22 at 02:35
  • Yes indeed, but I would say that this example is irrelevant to the real problem you're having. If you want to know how to read Data as Int16 you should ask about that. But note that such a question will probably be a duplicate of https://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data – matt Feb 23 '22 at 02:37
  • I apologize my intent was to give a working example. Obviously that only served to create more confusion because it was a poor example. – kka41 Feb 23 '22 at 02:50
  • Also known as an x-y question. Nevertheless I think I showed you quite clearly why the characters "1" and "0" don't magically convert thru a Data to integer bits. – matt Feb 23 '22 at 03:06

1 Answers1

0

It's unclear why you expect the .utf8 view of a string to have anything at all to do with its interpretation as an integer. These are characters, not bits (or digits). You have a sequence of 48 and 49 bytes, which naturally is not going to get you anything like the actual number. To see this, just say

for c in y { print(c) }

By the way, the usual way to convert a string to Data is

let y = x.data(using: .utf8)

and the way to convert it back is

let str = String(data: y!, encoding: .utf8)
matt
  • 515,959
  • 87
  • 875
  • 1,141