objective c - Get the first 32 bit (4 byte) number from NSString -
my nsstring looks this:
42949672951365185178
it concatenation of 32 bit number 4294967295
, timestamp 1365185178
.
i need split 2 can number , timestamp separately. know first 32 bits "number" part , rest timestamp.
this have tried:
nsstring *step9string = @"42949672951365185178"; nsdata *step10uandts = [step9string datausingencoding:nsasciistringencoding]; nsrange uidrange = nsmakerange(0, 4); // 4 bytes uint8 uidbytes[uidrange.length]; [step10uandts getbytes:&uidbytes range:uidrange]; nsdata *uiddata = [nsdata datawithbytes:uidbytes length:sizeof(uidbytes)]; nsstring *uid = [[nsstring alloc] initwithdata:uiddata encoding:nsasciistringencoding]; // , rest should timestamp nsrange tsrange = nsmakerange(4, step10uandts.length-4); uint8 tsbytes[tsrange.length]; [step10uandts getbytes:&tsbytes range:tsrange]; nsdata *tsdata = [nsdata datawithbytes:tsbytes length:sizeof(tsbytes)]; nsstring *ts = [[nsstring alloc] initwithdata:tsdata encoding:nsasciistringencoding]; nslog(@"uid: %@, ts: %@", uid, ts);
however i'm getting output:
uid: 4294, ts: 9672951365185466
not sure going wrong here, or how differently. if explain i'm doing wrong , how remedy i'll grateful.
thanks
moving info comments answer.
there's no way solve problem without 1 of 2 parts having known string length, because decimal representation of integer fits in 32 bits can have anywhere 1 10 digits long. example, strings 01365185178
or 45981365185466
fit constraints written -- 32-bit number, 0
or 4598
, followed timestamp. how determine "first 4 bytes" ends, though? in first case it's 1 character, in second it's four.
if in fact know length of 1 of them, simple slicing string. since you've indicated uid portion must zero-padded, looks this:
nsstring * uid = [step9string substringtoindex:10]; nsstring * timestamp = [step9string substringfromindex:10];
what's going wrong information in string made of characters, each of takes 1 byte. when put information nsdata
object, it's still characters -- there's no automatic conversion binary int
. need nsscanner
object or scanf()
or similar that. therefore, when access first 4 bytes of data object, you're getting first 4 characters of original string.
Comments
Post a Comment