Convert string to array of integers

0

Good morning. I have a String of binary numbers type "001010100101011111011010101101010000001110101011" in a file, which I read using the following code:

public String muestraContenido(String archivo) throws FileNotFoundException, IOException {
  String linea ="";
  FileReader fr = null;
  int[] binaryValue = new int [257];
  BufferedReader br = null;
    try {


     // Apertura del fichero y creacion de BufferedReader para poder
     // hacer una lectura comoda (disponer del metodo readLine()).
     File archivo1 = new File ("cadenaAleatoria.txt");
     fr = new FileReader (archivo);
     br = new BufferedReader(fr);
     String caracter="";
     //int[] cadena=new int[257];


     // Lectura del fichero

     //int i=0;
     while((caracter = br.readLine())!=null){
           // caracter=br.read();
            //binaryValue[i]=caracter;

        linea=caracter + br.readLine();


     br.close();

  }
  }catch(Exception e){
     e.printStackTrace();
  }finally{
     // En el finally cerramos el fichero, para asegurarnos
     // que se cierra tanto si todo va bien como si salta 
     // una excepcion.
     try{                    
        if( null != fr ){   
           fr.close();     
        }                  
     }catch (Exception e2){ 
        e2.printStackTrace();
     }
  }
  // mostrar(linea);

     return linea;

}

Well, what I want to do is pass this String that I just read, to an array of int[] . My idea is to convert this String into a int and later into a int[] . This would be possible ? Any better alternative than this?

    
asked by Juan Alvarez 18.12.2017 в 22:48
source

3 answers

0

Here I send you a code to solve the conversion:

public int[] conversor(String texto){
  texto = "001010100101011111011010101101010000001110101011";
  int digital[] = new int[texto.length()]; // estableciendo capacidad del arreglo con la longitud del texto
  int indice = 0;

  for(char valor : texto.toCharArray()){ // recorriendo caracteres del texto
      digital[indice] = Integer.valueOf(valor) - 48; // convirtiendo el caracter en numero respetando la tabla ASCII
      indice++;
  }

  //mostrando resultados
  for(int x : digital){
      System.out.println("valor: "+x);
  }

   return digital;
  }

and this other suggestion code to read a flat text file more efficiently

public void cargarArchivo(String direccion){
   List<String> lineas = new ArrayList<>();

    try {
        Path ruta = Paths.get(direccion);
        //Stream<String> flujoStrings = Files.lines(ruta);
        Stream<String> flujoFormateado = Files.lines(ruta, Charset.forName("UTF-8")); // cargando el archivo plano
        flujoFormateado.forEach(lineas::add); // almacenando todos los elementos para su analisis

        System.out.println("lineas guardadas: "+lineas.size());
    } catch (IOException ex) {
        Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
    }
}
    
answered by 18.12.2017 в 23:35
0

Maybe this would work for you:

public int[] parse(String num){
    int[] nums = new int[num.length()];
    for(int i=0; i<num.length(); i++){
        nums[i] = Character.getNumericValue(num.charAt(i));
    }
    return nums;
}
    
answered by 21.12.2017 в 01:46
0

Something quick would be:

String cadena = "001010100101011111011010101101010000001110101011";
char[] cadenaSeparada = cadena.toCharArray();//Conviertes la cadena en arreglo de tipo char
int[] enEnteros = new int[cadenaSeparada.length];//Creas una de entero con la misma longitud
    for (int i = 0; i < cadenaSeparada.length; i++) {
        enEnteros[i] = Character.getNumericValue(cadenaSeparada[i]);//Conviertes el char en int
    }
    
answered by 26.07.2018 в 08:37