Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stridewithout sacrificing speed?
Convert MB to byte - Conversion of Measurement Units
First note that your code does not detect invalid input data. For example, the string "XX" is just converted to a zero byte. Detecting invalid input with strtoul is a bit tricky, there is an alternative suggestion below.
This does not change the performance. The time to convert acharacter string is 0. I do not see an use-case for map here. But the performance can be improved considerably. As observed here and hereaccessing the UTF view of a Swift string is very fast.
This leads to the following implementation:. Note that invalid input is still not detected. We can still make it faster by converting the UTF code points "manually" instead of using strtoul.
How to convert Data to a String
This is more code, but again faster, and also detects all kinds of invalid input:. The time to convert thecharacter string is now 0. This is more than 17 times faster than the original code. Sign up to join this community.How to convert Data to a String – Swift 5
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. This is my code to convert byte data to float. I tried every answers given in this site. To get the number back from the data, you have to read it into an UInt32 first, convert from big-endian to host byteorder, and then cast the result to a Float. In Swift 5 the withUnsafeBytes method of Data calls the closure with an untyped UnsafeRawBufferPointerand you can load the value from the raw memory:.
Learn more. How to convert bytes to a float value in swift? Ask Question. Asked 3 years, 4 months ago. Active 8 months ago. Viewed 5k times. Nisha Nair Nisha Nair 5 5 silver badges 13 13 bronze badges. What value do you expect? If that is not what you expect then tell us what the result should be and why. Otherwise we can only guess.
Value should be Btw, you asked a similar question some time ago: stackoverflow. If an answer does not work for you then you can leave a comment and ask for clarification. Active Oldest Votes. Martin R Martin R k 71 71 gold badges silver badges bronze badges. Thanks a lot martin. MartinR Can you please add reverse of this process, means float to bytesIt's very urgent. Int' 0xdbd1a0 to 'Swift. UInt8' 0xdbc What swift version do you use? Sign up or log in Sign up using Google.
Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Featured on Meta. Community and Moderator guidelines for escalating issues via new response….
How to use Data withUnsafeMutableBytes in Swift 3
Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. With some buffer pointer magic you can avoid the intermediate copy to an NSData object Swift 2 :. I think Martin's answer is better than this, but I still want to post mine. Any suggestion would be really helpful. It's also just as generic for all the datatype sizes.
Note that MemoryLayout is only being used a sanity check. So when you have an array of 2 unsinged bytes and want to convert it a unsinged short you can simply. As [UInt8] is stored in a contiguous region of memory, there's no need to convert it to Datapointer can access all bytes directly.
Int 's byte order is little endian currently on all Apple platform, but this is not garanteed on other platforms. The problem with the accepted answer comes when you don't know the size of your bytes array or your Data size.
For those who prefer to do it the old-fashioned way, here's a set of methods for getting int values from a byte array. This is intended for situations where a byte array containing various kinds of data is being processed sequentially. This is an extract from a larger class that includes methods for extracting strings and other kinds of data. Learn more. Asked 4 years, 6 months ago. Active 3 months ago. Viewed 36k times.
How to convert a 4-bytes array into the corresponding Int?
Jerry Jerry 1, 1 1 gold badge 15 15 silver badges 29 29 bronze badges. MartinR Thanks for replying on my other posts. But so far none of them are actually solved. Active Oldest Votes.
There are two problems: Int is a bit integer on bit platforms, your input data has only bit.GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. Already on GitHub? Sign in to your account. In a minimal iOS application there is the Swift code. However, the printed values are not what I would expect. The data is correctly passed to the Go functions and back to Swift, but internally constructing the Bytes object it somehow changes. If I rewrite the constructor in Go as. I'm not sure whether this is a bug or expected but unpleasant behavior due to Go's and Swift's handling of values and references.
If the latter is true I really have no idea how to solve this issue on the Swift side in order to utilize Go libraries using byte at any interface function.
CC hyangah eliasnaur steeve. My guess but it's just a guess would be that the gomobile bindings are passing in a slice that aliases Swift-owned memory, and because objects in Go's heap are not visible to the Swift reference counters that memory is getting freed upon return. In other words: I suspect a classic use-after-free bug, obscured by the use of two garbage collectors. The usual fix for such a bug is to extend the aliased object for the lifetime of the alias. In a reference-counted language, that would imply pinning the Data reference for the lifetime of the returned Bytes object.
This is interesting since now NSMutableData is used which executes the branch where the data is actually not copied. After some more investigation I am now pretty sure what the actual problematic behavior is. These are the steps happening in my small example from the issue description:.
Actually I was wondering why gobind would copy at all. I'm actually thinking byte passed to Go functions should never be copied, and it's the responsibility of the callee to copy if they want to retain that data. But it's getting complex Skip to content. Dismiss Join GitHub today GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Sign up. New issue. Jump to bottom. Labels ExpertNeeded NeedsInvestigation mobile. Milestone Unreleased. Copy link Quote reply. What version of Go are you using go version? What operating system and processor architecture are you using go env? Println " Getter: "bytes. This comment has been minimized.A static byte buffer that bridges to Data ; use NSData when you need reference semantics or other Foundation-specific behavior. Data objects let simple allocated buffers that is, data with no embedded pointers take on the behavior of Foundation objects.
See Toll-Free Bridging for more information on toll-free bridging. NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location. When you work with a publicly accessible file, treat that file as an untrusted and potentially dangerous resource.
An attacker may compromise or corrupt these files. The attacker can also replace the files with hard or symbolic links, causing your write operations to overwrite or corrupt other system resources.
Avoid using the write to: atomically: method and the related methods when working inside a publicly accessible directory. Instead, use File Handle with an existing file descriptor to securely write the file. Initializes a data object filled with a given number of bytes of data from a given buffer, with a custom deallocator block.
Initializes a newly allocated data object by adding the given number of bytes from the given buffer. Returns a new data object containing the data object's bytes that fall within the limits specified by a given range. Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options. A dynamic byte buffer that bridges to Data ; use NSMutable Data when you need reference semantics or other Foundation-specific behavior.
Language: Swift Objective-C. Class NSData. SDKs iOS 2. Framework Foundation. Topics Creating Data. Reading Data from a File. Reading Options Initializes a data object with the content of the file at a given path.I had Xcode 8 convert my code to Swift 3. It changed all occruances of NSData to Data.
In my Swift 2 code I had:. There isn't much documentation yet and I can't figure out how to properly use withUnsafeMutableBytes. Are there any examples of how to use withUnsafeMutableBytes? If you want to work with beta software, you need to work with incomplete documetation and no example codes.
I've developed macOS and iOS code for close to 20 years and used a lot of beta software with and without documentaiton, but I was having difficulty with this syntax in Swift.
Thanks again. But this was very helpful for me. Just want to point out that withUnsafeBytes is a throwing function and actually needs a try in front of it. Which is pretty cool. But after converting to Swift 3 and fully embracing the new Data type, I've not found much need for it. What specifically are you needing to do? This is code that accesses the CommonCrypto framework.
What do you think about encapsulating the two function in a class, e. ByteBackPacker and convert them to class functions? What about giving byteOrder: ByteOrder a default value, e. Update: I created a ByteBackpacker project on github. Let me know what you think about it. Using a dedicated enumeration type ByteOrder is a good idea.
If you don't pass the type in the unpack function then the compiler has to infer it from the context and either of these would work:. I think it is a matter of taste which version you choose, I would prefer passing the type explicitly. Encapsulating the functions into a type is also a good idea. But I would use a struct which is initialized with the byte order, and make that instance methods and not class methods. The reason is that you probably will do several calls with the same byte order and you don't have to pass it to every call:.
Your code assumes that the host byte order is little-endian, which is the case for all current OS X and iOS platforms. On the other hand, Swift is open source now and people already start to port it to different platforms.
I have no idea if Swift will be ported to a big-endian platform at some time. Note that the static property hostByteOrder is computed only once in the lifetime of the app, not each time that it is used.
There is — as far as I know — no protocol which comprises all integer and floating point types. What you could do is to define a protocol.
I'm working my way through Martin's very useful answer. I have discovered one small simplification. The ByteOrder enum is not required. NSHostByteOrder can be used:. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. Type to byte array conversion in Swift Ask Question.
Asked 4 years, 3 months ago. Active 4 years ago. Viewed 9k times. Especially I am interested in your opinion on CFByteOrder does offer already a byte order, but I decided to go with a different definition. LittleEndian Is the following nicer? I don't think so, but what about you.