16进制转2进制字符串 ios

2015-10-25 20:24:59 wang1018960145 阅读数 4040
二进制流对于我们程序员来说不陌生,但是看起来那是相当困难,近期学习了一些进制的转换,希望对大家有用
/**
 *  将二进制数据转换成十六进制字符串
 *
 *  @param data 二进制数据
 *
 *  @return 十六进制字符串
 */
+ (NSString *)data2Hex:(NSData *)data {
    if (!data) {
        return nil;
    }
    Byte *bytes = (Byte *)[data bytes];
    NSMutableString *str = [NSMutableString stringWithCapacity:data.length * 2];
    for (int i=0; i < data.length; i++){
        [str appendFormat:@"%0x", bytes[i]];
    }
    return str;
}


将二进制数据转换成16进制的字符串,


2015-08-28 15:41:01 kongu 阅读数 3217

iOS 二进制数组转成16进制字符串

 Byte bytes[28];
 [data getBytes:bytes length:28];

 NSMutableString *hexString = [[NSMutableString alloc] init];
 for (int i = 0; i < 28; i++) {
      NSLog(@"%hhu",bytes[i]);
      [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", bytes[i]]];
 }

 NSLog(@" %@  ", hexString);

字符串转二进制

int len = [self length] / 2;    // Target length  
unsigned char *buf = malloc(len)  
unsigned char *whole_byte = buf;  
char byte_chars[3] = {'\0','\0','\0'};  

int i;  
for (i=0; i < [self length] / 2; i++) {  
    byte_chars[0] = [self characterAtIndex:i*2];  
    byte_chars[1] = [self characterAtIndex:i*2+1];  
    *whole_byte = strtol(byte_chars, NULL, 16);  
    whole_byte++;  
}  

NSData *data = [NSData dataWithBytes:buf length:len];  
free( buf );  
return data; 
2014-10-28 12:52:46 u011662420 阅读数 810


1:iOS字符串和16进制之间的相互转换

首先,介绍一下字符串转换成字符串

在 *.h 中:

/**
 *    @brief    字符串转换成16进制的字符
 *
 *    @param     string     要转换的字符串
 *
 *    @return    返回得到的16进制字符串
 */
+ (NSString *)hexStringFromString:(NSString *)string;

在 *.m 中:

/**
 *    @brief    字符串转换成16进制
 *
 */
+ (NSString *)hexStringFromString:(NSString *)string

{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];//16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
    }
    return hexStr; 
}

 

这样就OK了,简单吧,接下来看16进制转换成字符串

在 .h 中

/**
 *    @brief    16进制的字符转换成字符串
 *
 *    @param     string     要转换的字符串
 *
 *    @return    返回得到的字符串
 */
+ (NSString *)stringFromHexString:(NSString *)hexString;

 

在  . m中

+ (NSString *)stringFromHexString:(NSString *)hexString
{
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for(int i = 0; i < [hexString length] - 1; i += 2){
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[[NSScanner alloc] initWithString:hexCharStr] autorelease];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    NSLog(@"------字符串=======%@",unicodeString);
    return unicodeString;

}


2:ios开发之16进制颜色(html颜色值)字符串转为UIColor


+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) 
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) 
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6) 
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}


// rgb颜色转换(16进制->10进制)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]





2018-06-09 16:55:46 qq8864 阅读数 5147

Java版:

private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }

c语言版:

/**
* hex格式char转二进制
*/
unsigned char hex_of_char(char c) {
	unsigned char tmp = 0;
	if(c >= '0' && c <= '9') {
		tmp = (c - '0');
	}
	else if(c >= 'A' && c <= 'F') {
		tmp = (c - 'A' + 10);
	}
	else if(c >= 'a' && c <= 'f') {
		tmp = (c - 'a' + 10);
	}
	return tmp;
}
static char g_hex_map_table[] = "0123456789ABCDEF";
/**
* 字节数组转hex格式字符串
* @param print_buf: 十六进制字符串buffer
* @param print_buf_len: 十六进制字符串buffer长度
* @param bytes: 二进制数据
* @param bytes_len: 二进制数据长度
*/
char* bytes_to_hex_string(
	char* print_buf, 
	int print_buf_len, 
	const unsigned char* bytes, 
	int len) {

	int i = 0;

	/**
	* 入参校验
	*/ 
	if(print_buf == NULL || bytes == NULL || (len * 2 + 1) > print_buf_len) {
		return NULL;
	}

	for(i = 0; i < len; i++) {
		print_buf[i * 2] = g_hex_map_table[(bytes[i] >> 4) & 0x0F];
		print_buf[i * 2 + 1] = g_hex_map_table[(bytes[i]) & 0x0F];
	}
	/**
	* 填充字符串结束符
	*/
	print_buf[i * 2] = '\0';
	/**
	* 返回目标地址
	*/
	return print_buf;
}
/**
* hex格式字符串转字节数组
* @param hex_string: 十六进制字符串
* @param hex_string_len: 十六进制字符串长度
* @param bytes: 二进制数据存储空间
* @param bytes_len: 目标空间长度
*/
int hex_string_to_bytes(
	char* hex_string, 
	int hex_string_len, 
	unsigned char* bytes, 
	int bytes_len) {
	
	int i = 0;

	/**
	* 校验十六进制字符串长度必须偶数,并且目标存储空间必须足够存放转换后的二进制数据
	*/
	if((hex_string_len % 2 != 0) || (bytes_len * 2 < hex_string_len)) {
		return -1;
	}
	
	for(i = 0; i < hex_string_len; i += 2) {
		bytes[i/2] = ((hex_of_char(hex_string[i]) << 4) & 0xF0) | 
					(hex_of_char(hex_string[i + 1]) & 0x0F);
	}
	return 1;
}