Hello I am trying to figure out how convert / decode a base64 string in an iOS application to NSData, so I can decrypt the data that I encrypted.
The method I used for converting the NSData to a base 64 string can be found here Is there a similar way to create method to decode / convert the base 64 string to NSData?
This is what I was looking for.
+ (NSData *)base64DataFromString: (NSString *)string
{
unsigned long ixtext, lentext;
unsigned char ch, inbuf[4], outbuf[3];
short i, ixinbuf;
Boolean flignore, flendtext = false;
const unsigned char *tempcstring;
NSMutableData *theData;
if (string == nil)
{
return [NSData data];
}
ixtext = 0;
tempcstring = (const unsigned char *)[string UTF8String];
lentext = [string length];
theData = [NSMutableData dataWithCapacity: lentext];
ixinbuf = 0;
while (true)
{
if (ixtext >= lentext)
{
break;
}
ch = tempcstring [ixtext++];
flignore = false;
if ((ch >= 'A') && (ch <= 'Z'))
{
ch = ch - 'A';
}
else if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 'a' + 26;
}
else if ((ch >= '0') && (ch <= '9'))
{
ch = ch - '0' + 52;
}
else if (ch == '+')
{
ch = 62;
}
else if (ch == '=')
{
flendtext = true;
}
else if (ch == '/')
{
ch = 63;
}
else
{
flignore = true;
}
if (!flignore)
{
short ctcharsinbuf = 3;
Boolean flbreak = false;
if (flendtext)
{
if (ixinbuf == 0)
{
break;
}
if ((ixinbuf == 1) || (ixinbuf == 2))
{
ctcharsinbuf = 1;
}
else
{
ctcharsinbuf = 2;
}
ixinbuf = 3;
flbreak = true;
}
inbuf [ixinbuf++] = ch;
if (ixinbuf == 4)
{
ixinbuf = 0;
outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
for (i = 0; i < ctcharsinbuf; i++)
{
[theData appendBytes: &outbuf[i] length: 1];
}
}
if (flbreak)
{
break;
}
}
}
return theData;
}
Related
I wrote a code to print the length of the longest line from my input and print out as much as possible of the longest line(There is a maximum length of what I can output the longest line). But I got this error. I tried everything I could yet still no clue. Is there anyone who might help?
#include<stdio.h>
#define MAXLINE 10
int getline(char line[], int len) {
int i,c,max;
i = 0;
max = 0;
while ((c = getchar()) != EOF&&c!='\n') {
if (i < len) {
line[i] = c;
}
i += 1;
}
if (i < len) {
if (c == '\n') {
line[i] = c;
i += 1;
}
line[i] = '\0';
}
else if (i >= len) {
line[len] = '\0';
}
return i;
}
void copy(char from[], char to[]) {
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
i += 1;
}
to[i] = '\0';
}
main() {
char longline[MAXLINE];
char longestline[MAXLINE];
char maxlong[MAXLINE];
int length;
int max = 0;
int maxline = 0;
while ((length = getline(longline, MAXLINE)) > 0) {
if (length > max && length < MAXLINE) {
copy(longline, longestline);
max = length;
}
else if (length > MAXLINE) {
if (length > maxline) {
maxline = length;
copy(longline, maxlong);
}
}
}
if (maxline == 0) {
printf("%s", longestline);
}
else {
printf("%s\n%d\n", maxlong, maxline);
}
}
i have a code in c# for aes decryption
i want make same encryption result by objective-c
but i failed.. help me
i can fix objective-c code, what can i for this?
c# for decrypt
private static readonly string AES_KEY = "asdfasdfasdfasdf";
private static readonly int BUFFER_SIZE = 1024 * 4;
private static readonly int KEY_SIZE = 128;
private static readonly int BLOCK_SIZE = 128;
static public string Composite(string value)
{
using (AesManaged aes = new AesManaged())
using (MemoryStream ims = new MemoryStream(Convert.FromBase64String(value), false))
{
aes.KeySize = KEY_SIZE;
aes.BlockSize = BLOCK_SIZE;
aes.Mode = CipherMode.CBC;
aes.Key = Encoding.UTF8.GetBytes(AES_KEY);
byte[] iv = new byte[aes.IV.Length];
ims.Read(iv, 0, iv.Length);
aes.IV = iv;
using (ICryptoTransform ce = aes.CreateDecryptor(aes.Key, aes.IV))
using (CryptoStream cs = new CryptoStream(ims, ce, CryptoStreamMode.Read))
using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Decompress))
using (MemoryStream oms = new MemoryStream())
{
byte[] buf = new byte[BUFFER_SIZE];
for (int size = ds.Read(buf, 0, buf.Length); size > 0; size = ds.Read(buf, 0, buf.Length))
{
oms.Write(buf, 0, size);
}
return Encoding.UTF8.GetString(oms.ToArray());
}
}
}
objective-c for encrypt
- (NSString *)AES128EncryptWithKey:(NSString *)key
{
NSData *plainData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [plainData AES128EncryptWithKey:key];
NSString *encryptedString = [encryptedData stringUsingEncodingBase64];
return encryptedString;
}
#import "NSData+AESCrypt.h"
#import <CommonCrypto/CommonCryptor.h>
static char encodingTable[64] =
{
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};
#implementation NSData (AESCrypt)
- (NSData *)AES128EncryptWithKey:(NSString *)key
{
// 'key' should be 16 bytes for AES128
char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCModeCBC | kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free( buffer ); //free the buffer
return nil;
}
- (NSString *)base64Encoding
{
const unsigned char *bytes = [self bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:self.length];
unsigned long ixtext = 0;
unsigned long lentext = self.length;
long ctremaining = 0;
unsigned char inbuf[3], outbuf[4];
unsigned short i = 0;
unsigned short charsonline = 0, ctcopy = 0;
unsigned long ix = 0;
while( YES )
{
ctremaining = lentext - ixtext;
if( ctremaining <= 0 ) break;
for( i = 0; i < 3; i++ )
{
ix = ixtext + i;
if( ix < lentext ) inbuf[i] = bytes[ix];
else inbuf [i] = 0;
}
outbuf [0] = (inbuf [0] & 0xFC) >> 2;
outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4);
outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6);
outbuf [3] = inbuf [2] & 0x3F;
ctcopy = 4;
switch( ctremaining )
{
case 1:
ctcopy = 2;
break;
case 2:
ctcopy = 3;
break;
}
for( i = 0; i < ctcopy; i++ )
[result appendFormat:#"%c", encodingTable[outbuf[i]]];
for( i = ctcopy; i < 4; i++ )
[result appendString:#"="];
ixtext += 3;
charsonline += 4;
}
return [NSString stringWithString:result];
}
------------------------------------------------------------
------------------------------------------------------------
In my app I have to implement a form which works offline as well.
There are some images to be uploaded in the form. The way I currently implement is by first saving the image in Application directory. And saving it's file location in database then delete it when I upload. This process is too lengthy and mind boggling. What do you guys suggest? Should I save it the image as Data in sqlite instead or this approach i took is better.
This is how I implemented it:
ALAssetsLibrary *lib=[ALAssetsLibrary new];
for (int i=0; i<assets.count; i++) {
ALAsset *asset=assets[i];
NSString *baseDir=[fileMgr GetDocumentDirectory];
//STORING FILE INTO LOCAL
[lib assetForURL:asset.defaultRepresentation.url
resultBlock:^(ALAsset *asset){
ALAssetRepresentation *repr = [asset defaultRepresentation];
CGImageRef cgImg = [repr fullResolutionImage];
NSString *fname = repr.filename;
UIImage *img = [UIImage imageWithCGImage:cgImg];
NSData *data = UIImagePNGRepresentation(img);
[data writeToFile:[baseDir stringByAppendingPathComponent:fname]
atomically:YES];
//FOR LOCAL URL OF THE IMAGE
NSString *imageURL = [baseDir stringByAppendingPathComponent:fname];
NSLog(#"%# URL OF IMAGE ",imageURL);
}
failureBlock:^(NSError *error){
}];
}
NSLog(#"COPIED %lu FILE INTO LOCAL MEMORY",(unsigned long)assets.count);
yes you can save the image in database as a string. create an catagory NSString+NSStringAdditions.h like this.
//
// NSString+NSStringAdditions.h
// RemoteControl
//
// Created by Bhaskar on 09/05/14.
// Copyright (c) 2014 Bhaskar. All rights reserved.
//
#import <Foundation/Foundation.h>
#interface NSString (NSStringAdditions)
+ (NSString *) base64StringFromData:(NSData *)data length:(int)length;
+ (NSData *) base64DataFromString:(NSString *)string;
#end
//
// NSString+NSStringAdditions.m
// RemoteControl
//
// Created by Bhaskar on 09/05/14.
// Copyright (c) 2014 Bhaskar. All rights reserved.
//
#import "NSString+NSStringAdditions.h"
static char base64EncodingTable[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
#implementation NSString (NSStringAdditions)
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
unsigned long ixtext, lentext;
long ctremaining;
unsigned char input[3], output[4];
short i, charsonline = 0, ctcopy;
const unsigned char *raw;
NSMutableString *result;
lentext = [data length];
if (lentext < 1)
return #"";
result = [NSMutableString stringWithCapacity: lentext];
raw = [data bytes];
ixtext = 0;
while (true) {
ctremaining = lentext - ixtext;
if (ctremaining <= 0)
break;
for (i = 0; i < 3; i++) {
unsigned long ix = ixtext + i;
if (ix < lentext)
input[i] = raw[ix];
else
input[i] = 0;
}
output[0] = (input[0] & 0xFC) >> 2;
output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
output[3] = input[2] & 0x3F;
ctcopy = 4;
switch (ctremaining) {
case 1:
ctcopy = 2;
break;
case 2:
ctcopy = 3;
break;
}
for (i = 0; i < ctcopy; i++)
[result appendString: [NSString stringWithFormat: #"%c", base64EncodingTable[output[i]]]];
for (i = ctcopy; i < 4; i++)
[result appendString: #"="];
ixtext += 3;
charsonline += 4;
if ((length > 0) && (charsonline >= length))
charsonline = 0;
}
return result;
}
+ (NSData *)base64DataFromString: (NSString *)string
{
unsigned long ixtext, lentext;
unsigned char ch, inbuf[4], outbuf[3];
short i, ixinbuf;
Boolean flignore, flendtext = false;
const unsigned char *tempcstring;
NSMutableData *theData;
if (string == nil)
{
return [NSData data];
}
ixtext = 0;
tempcstring = (const unsigned char *)[string UTF8String];
lentext = [string length];
theData = [NSMutableData dataWithCapacity: lentext];
ixinbuf = 0;
while (true)
{
if (ixtext >= lentext)
{
break;
}
ch = tempcstring [ixtext++];
flignore = false;
if ((ch >= 'A') && (ch <= 'Z'))
{
ch = ch - 'A';
}
else if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 'a' + 26;
}
else if ((ch >= '0') && (ch <= '9'))
{
ch = ch - '0' + 52;
}
else if (ch == '+')
{
ch = 62;
}
else if (ch == '=')
{
flendtext = true;
}
else if (ch == '/')
{
ch = 63;
}
else
{
flignore = true;
}
if (!flignore)
{
short ctcharsinbuf = 3;
Boolean flbreak = false;
if (flendtext)
{
if (ixinbuf == 0)
{
break;
}
if ((ixinbuf == 1) || (ixinbuf == 2))
{
ctcharsinbuf = 1;
}
else
{
ctcharsinbuf = 2;
}
ixinbuf = 3;
flbreak = true;
}
inbuf [ixinbuf++] = ch;
if (ixinbuf == 4)
{
ixinbuf = 0;
outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
for (i = 0; i < ctcharsinbuf; i++)
{
[theData appendBytes: &outbuf[i] length: 1];
}
}
if (flbreak)
{
break;
}
}
}
return theData;
}
#end
I've to implement the RC4 encryption algorithm in my application for URL encoding.The sample part is listed below for your reference.
Actual value Before Encryption : 10/28/2013
Expected value After Encryption : ˆ!˜·hÇÔÞò
After URL encoding it should be : %0C%88%21%98%B7h%C7%D4%DE%F2
KEY USED is:#"psw"
I've tried but value after encryption & URL encoding returns in this way:
After encryption : !·hÇÔÞò
After URL encoding : %0C%C2%88%21%C2%98%C2%B7h%C3%87%C3%94%C3%9E%C3%B2
I tried converting the java code into objective c code.The java code works fine ,were as the objective c is not working, which you can see in the above result.
Here is the Java code
import java.net.URLEncoder;
public class RC4 {
private char[] key;
private int[] sbox;
private static final int SBOX_LENGTH = 256;
private static final int KEY_MIN_LENGTH = 1;
public static void main(String[] args) {
try {
RC4 rc4 = new RC4("psw");
char[] result = rc4.encrypt("10/28/2013".toCharArray());
System.out.println("encrypted string:\n"
+ new String(toByteArray(result)));
System.out.println("decrypted string:\n"
+ new String(rc4.decrypt(result)));
System.out.println("decrypted string:\n"
+ URLEncoder.encode(new String(toByteArray(result))));
} catch (InvalidKeyException e) {
System.err.println(e.getMessage());
}
}
static byte[] toByteArray(char[] chars) {
byte[] bytes = new byte[chars.length];
for (int i = 0; i < chars.length; i++) {
// bytes[i*2] = (byte) (chars[i] >> 8);
bytes[i] = (byte) chars[i];
}
return bytes;
}
public RC4(String key) throws InvalidKeyException {
setKey(key);
}
public RC4() {
}
public char[] decrypt(final char[] msg) {
return encrypt(msg);
}
public char[] encrypt(final char[] msg) {
sbox = initSBox(key);
char[] code = new char[msg.length];
int i = 0;
int j = 0;
for (int n = 0; n < msg.length; n++) {
i = (i + 1) % SBOX_LENGTH;
j = (j + sbox[i]) % SBOX_LENGTH;
swap(i, j, sbox);
int rand = sbox[(sbox[i] + sbox[j]) % SBOX_LENGTH];
code[n] = (char) (rand ^ (int) msg[n]);
}
return code;
}
private int[] initSBox(char[] key) {
int[] sbox = new int[SBOX_LENGTH];
int j = 0;
for (int i = 0; i < SBOX_LENGTH; i++) {
sbox[i] = i;
}
for (int i = 0; i < SBOX_LENGTH; i++) {
j = (j + sbox[i] + key[i % key.length]) % SBOX_LENGTH;
swap(i, j, sbox);
}
return sbox;
}
private void swap(int i, int j, int[] sbox) {
int temp = sbox[i];
sbox[i] = sbox[j];
sbox[j] = temp;
}
public void setKey(String key) throws InvalidKeyException {
if (!(key.length() >= KEY_MIN_LENGTH && key.length() < SBOX_LENGTH)) {
throw new InvalidKeyException("Key length has to be between "
+ KEY_MIN_LENGTH + " and " + (SBOX_LENGTH - 1));
}
this.key = key.toCharArray();
}
public class InvalidKeyException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidKeyException(String message) {
super(message);
}
}
}
Its corresponding Objective c Code
-(NSString *)encrypt:(NSString *)string{
[self frameSBox:#"psw"];
unichar code[string.length];
const unichar* buffer = code;
int i = 0;
int j = 0;
for (int n = 0; n < string.length; n++) {
i = (i + 1) % self.SBOX_LENGTH;
j = (j + [[self.sBox objectAtIndex:i]integerValue]) % self.SBOX_LENGTH;
[self swap:i with:j];
int index=([[self.sBox objectAtIndex:i] integerValue]+[[self.sBox objectAtIndex:j] integerValue]);
int rand=([[self.sBox objectAtIndex:(index%self.SBOX_LENGTH)] integerValue]);
code[n]=(rand ^ (int)[string characterAtIndex:n]);
}
buffer = code;
return [NSString stringWithCharacters:buffer length:string.length];
}
-(NSArray *)frameSBox:(NSString *)keyValue{
if (self.sBox == nil) {
self.sBox=[[NSMutableArray alloc]init];
}
self.SBOX_LENGTH=256;
int j = 0;
for (int i = 0; i < self.SBOX_LENGTH; i++) {
[self.sBox addObject:[NSNumber numberWithInteger:i]];
}
for (int i = 0; i < self.SBOX_LENGTH; i++) {
j = (j + [[self.sBox objectAtIndex:i] integerValue] + [keyValue characterAtIndex:(i % keyValue.length)]) % self.SBOX_LENGTH;
[self swap:i with:j];
}
return self.sBox;
}
-(void)swap:(int)i with:(int)j{
id tempObj = [self.sBox objectAtIndex:i];
[self.sBox replaceObjectAtIndex:i withObject:[self.sBox objectAtIndex:j]];
[self.sBox replaceObjectAtIndex:j withObject:tempObj];
}
//I'm calling in a different class by creating the RC4encryptor object
NSString *unescaped = [[RC4StringEncryptor encryptor] encrypt:#"10/28/2013"];
logDebug(#"the value is:%#",unescaped);
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) unescaped,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]\" "),
kCFStringEncodingUTF8));
NSLog(#"escapedString: %#",escapedString);
I've also tried
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (RC4)
- (NSData *)RC4EncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeMinRC4+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCKeySizeMinRC4;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmRC4, kCCModeRC4,
keyPtr, kCCKeySizeMinRC4,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] RC4EncryptWithKey:key];
}
But this above code doesn't work for me.Kindly help me in this....
Somehow I fixed your code and it encrypts-decrypts perfectly. Here it is:
#interface RC4Crypt()
#property (nonatomic, strong) NSArray * key;
#property (nonatomic, strong) NSMutableArray * sBox;
#end
#implementation RC4Crypt
static const int SBOX_LENGTH = 256;
static const int KEY_MIN_LENGTH = 1;
-(NSString *)encrypt:(NSString *)string withKey:(NSString *)key{
self.sBox = [[self frameSBox:key] mutableCopy];
unichar code[string.length];
int i = 0;
int j = 0;
for (int n = 0; n < string.length; n++) {
i = (i + 1) % SBOX_LENGTH;
j = (j + [[self.sBox objectAtIndex:i]integerValue]) % SBOX_LENGTH;
[self.sBox exchangeObjectAtIndex:i withObjectAtIndex:j];
int index=([self.sBox[i] integerValue]+[self.sBox[j] integerValue]);
int rand=([self.sBox[(index%SBOX_LENGTH)] integerValue]);
code[n]=(rand ^ (int)[string characterAtIndex:n]);
}
const unichar* buffer;
buffer = code;
return [NSString stringWithCharacters:buffer length:string.length];
}
- (NSString*) decrypt:(NSString*)string withKey:(NSString*)key
{
return [self encrypt:string withKey:key];
}
-(NSArray *)frameSBox:(NSString *)keyValue{
NSMutableArray *sBox = [[NSMutableArray alloc] initWithCapacity:SBOX_LENGTH];
int j = 0;
for (int i = 0; i < SBOX_LENGTH; i++) {
[sBox addObject:[NSNumber numberWithInteger:i]];
}
for (int i = 0; i < SBOX_LENGTH; i++) {
j = (j + [sBox[i] integerValue] + [keyValue characterAtIndex:(i % keyValue.length)]) % SBOX_LENGTH;
[sBox exchangeObjectAtIndex:i withObjectAtIndex:j];
}
return [NSArray arrayWithArray:sBox];
}
#end
I've writing an app that requires French language support. I'm having trouble getting currency to format correctly when the locale is set to FR. Is there any way to do this correctly?
I had to do it myself.
Created a "Formatter" class extending AFormatter with the following methods
Don't now how it is in France but in Argentina we use the following format 10.000.000,18 for example.
Hope it's helps or that someone provides a better solution
public static String addCommas(String s) {
int extraRound = 0;
boolean negative = false;
int c;
if(s.charAt(0) == '-') {
negative = true;
s = s.substring(1);
}
int len = s.indexOf('.')==-1?s.length():s.indexOf('.');
if(len > extraRound + 3) {
c = len - extraRound - 3;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 6) {
c = len - extraRound - 6;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 9) {
c = len - extraRound - 9;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 12) {
c = len - extraRound - 12;
s = s.substring(0, c) + "," + s.substring(c);
}
if(negative) {
s = '-' + s;
}
return s;
}
public static String addCommasNew(String s) {
int extraRound = 0;
boolean negative = false;
int c;
if(s.charAt(0) == '-') {
negative = true;
s = s.substring(1);
}
int len = s.indexOf(',')==-1?s.length():s.indexOf(',');
if(len > extraRound + 3) {
c = len - extraRound - 3;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 6) {
c = len - extraRound - 6;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 9) {
c = len - extraRound - 9;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 12) {
c = len - extraRound - 12;
s = s.substring(0, c) + "." + s.substring(c);
}
if(negative) {
s = '-' + s;
}
return s;
}
public static String removeScientific(String s) {
int eIndex = s.indexOf('E');
int initialPos = s.indexOf('.');
String result = s;
if (eIndex != -1){
int base = Integer.parseInt(s.substring(eIndex+1));
String pre = s.substring(0, initialPos);
String pos = s.substring(initialPos+1, eIndex);
String pos1 = "";
if (base < pos.length()){
String pos1a = pos.substring(0, base);
String pos1b = pos.substring(base, pos.length());
pos1 = pos1a + "." + pos1b;
} else {
pos1 = pos.substring(0, pos.length());
for (int i = 0; i < base-pos.length(); i++){
pos1 = pos1 + "0";
}
}
result = pre + pos1;
}
return result;
}
public static String changePointToComma(String s){
int initialPos = s.indexOf('.');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + "," + s.substring(initialPos + 1, s.length());
}
return result;
}
public static String changeCommaToPoint(String s){
int initialPos = s.indexOf(',');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + "." + s.substring(initialPos + 1, s.length());
}
return result;
}
public static String removeNumberFormat(String s){
int initialPos = s.indexOf('.');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + s.substring(initialPos + 1, s.length());
result = Formatter.removeNumberFormat(result);
} else {
return result = Formatter.changeCommaToPoint(s);
}
return result;
}
public static String roundDouble(String s, int presicion){
int initialPos = s.indexOf('.');
String result = s;
String pre;
String pos;
if (initialPos != -1){
pre = s.substring(0, initialPos);
pos = s.substring(initialPos + 1, s.length());
if (presicion < pos.length()){
pos = s.substring(initialPos + 1, initialPos + 1 + presicion );
int dec = Integer.parseInt(pos);
int next = Integer.parseInt(s.substring(initialPos + 1 + presicion, initialPos + 2 + presicion )); //to round the las digit
if (next > 4){
dec = dec + 1;
pos = dec + "";
if ((dec+"").length() > presicion){
pre = (Integer.parseInt(pre) + 1) + "";
pos = "0";
}
}
} else {
}
result = pre + "." + pos;
}
return result;
}