1

I am assembling a NSData object and I am getting the following

0100020000

This is what I want except for the leading zero. I need it to be

100020000

I tried the following code. But it leaves me with 00020000.

NSRange range = NSMakeRange(0, 1);
[byteRequest replaceBytesInRange:range withBytes:NULL length:0];

Any ideas? Thanks.

Brian Kalski
  • 897
  • 9
  • 35
  • 2
    It's hard to tell from your question what the data actually looks like. Are those strings of hex bytes? text? If it's hex bytes, then each *pair* of digits represents a single byte, which means you're trying to remove just half of a byte off the front-- that's not going to work without a lot of additional bit-twiddling. But that would be a pretty unusual requirement so my guess is that you're actually after something different. Can you elaborate on what the data represents and what you need? – Ben Zotto Nov 09 '15 at 20:01
  • It is a string of hex bytes. I figured out a better way to do it. I was converting each piece to NSData and appending it. If I convert the entire string to NSData instead it will fix my issue. Additional zeros at the end will be fine. Thanks. – Brian Kalski Nov 09 '15 at 20:15

1 Answers1

0

Given your description, you have the following 5 bytes:

1, 0, 2, 0, 0

You are somehow converting that to hex, which creates two-digits per byte:

"01 00 02 00 00"

But this is just a textual representation of the previous bytes. It is equivalent to all of these:

"0100020000"

"0x0100020000"

"4,295,098,368" (in decimal) "040000400000" (in octal)

And the one you appear to want: "100020000"

Just like "1.00" is equivalent to "1.0", "01" is equivalent to "1".

If your goal is to get a string of all the bytes as two-digit strings, except the first, which should only have as many digits as required, then here is an example of that:

 int bytes[5] = {1, 0, 2, 0, 0};
 NSString *str = [NSString stringWithFormat:@"%x%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4]];

You could use a loop and append these if the numbre of bytes is unknown. Start with %x and then use %02x for all the subsequent.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610