user774150
user774150

Reputation: 1072

Sending hexadecimal data to devices (Converting NSString to hexadecimal data)

I'm trying to send hexadecimal data via WiFi.

The code is something like this:

NSString *abc = @"0x1b 0x50";
NSData *data = [[[NSData alloc] initWithData:[abc dataUsingEncoding:NSASCIIStringEncoding]]autorelease];
[outputStream write:[data bytes] maxLength:[data length]]];

Instead of sending the hexadecimal data, it's sending it in text format. I tried with NSUTF8StringEncoding, but it's the same. I'm using it with the NSStream class.

Upvotes: 1

Views: 1424

Answers (2)

Shaggy Frog
Shaggy Frog

Reputation: 27601

You're not getting what you expect with NSString *abc = @"0x1b 0x50". It's almost the same as having NSString *abc = @"cat dog 123 0x0x0x"; just a bunch of words separated by spaces. So when you create your NSData object, you're just initializing it with a string of characters, not a series of actual numbers.

If you can get your numbers into an NSArray, this question/answer should help you: How to convert NSArray to NSData?

Upvotes: 2

richardolsson
richardolsson

Reputation: 4071

The data that you probably want to send is simply 0x1b50, which is the decimal number 6992 (assuming big-endian), and fits into two bytes. This is not the same as a string (which could contain anything) even if it happens to contain some human-readable representation of those numbers.

I'm assuming you want to send this as binary data, and if so one way would be to simply send a buffer formed by a single UInt16 instead of a string. I'm not very familiar with the relevant APIs, but look to see if you can populate the NSData with an integer, perhaps something like:

UInt16 i = 0x1b50; // Or = 6992
[[NSData alloc] initWithBytes: &i length: sizeof(i)]

[outputStream write: [data bytes] maxLength: [data length]]];

Again, I'm not fluent with Objective C, but this should be the general approach to sending the number 0x1b50 as binary data.

Upvotes: 0

Related Questions