Re: String in hexadecimal
Re: String in hexadecimal
- Subject: Re: String in hexadecimal
- From: j o a r <email@hidden>
- Date: Tue, 27 Jan 2004 08:19:44 +0100
On 2004-01-27, at 06.50, Jacob Chapa wrote:
>
Anyone know how to get a hexadecimal value of a string?
I guess it depends what you're looking for... How will you use the hex
value?
I've included one possible approach below, implemented as categories to
NSString and NSData.
You would use it like this:
NSString *plainString = @"Some string value";
NSString *hexString = [plainString hexStringRepresentation];
...and then back:
NSString *restoredString = [NSString stringWithHexString: hexString];
j o a r
===================================================================
@interface NSData (HexStringRepresentations)
+ (NSData *) dataWithHexString:(NSString *) hexString;
- (NSString *) hexStringRepresentation;
@end
@implementation NSData (HexStringRepresentations)
#define Dec2Hex(d) ((d) < 10 ? (d) + 48 : (d) - 10 + 'a')
#define Hex2Dec(x) ((x) >= '0' && (x) <= '9' ? (x) - 48 : (x) - 'a' +
10)
+ (NSData *) dataWithHexString:(NSString *) hexString
{
// We should never fail this test since the string passed to this
method
// should be a string created by the complementary method
"hexStringRepresentation"
// NSAssert([string
canBeConvertedToEncoding:NSASCIIStringEncoding], @"Assertion failure:
String cannot be converted to plain ASCII encoding.");
NSMutableData *data = [NSMutableData data];
const unsigned char *p = [hexString cString];
int i;
for (i = 0; i < [hexString cStringLength]; i += 2)
{
char d = Hex2Dec(p[i]) * 16 + Hex2Dec(p[i+1]);
[data appendBytes: &d length: 1]; // 1 == sizeof(char)
}
return data;
}
- (NSString *) hexStringRepresentation
{
NSMutableString *string = [NSMutableString string];
int i;
unsigned char *b = (unsigned char *)[self bytes];
for (i = 0; i < [self length]; i++)
{
[string appendFormat: @"%c%c", Dec2Hex(*b / 16), Dec2Hex(*b % 16)];
b++;
}
return string;
}
@end
@interface NSString (HexStringRepresentations)
+ (NSString *) stringWithHexString:(NSString *) hexString;
- (NSString *) hexStringRepresentation;
@end
#define kSTRING_ENCODING NSUnicodeStringEncoding
@implementation NSString (HexStringRepresentations)
+ (NSString *) stringWithHexString:(NSString *) hexString
{
NSData *data = [NSData dataWithHexString: hexString];
return [[[NSString alloc] initWithData: data encoding:
kSTRING_ENCODING] autorelease];
}
- (NSString *) hexStringRepresentation
{
return [[self dataUsingEncoding: kSTRING_ENCODING]
hexStringRepresentation];
}
@end
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.