WinFuture-Forum.de: [erledigt] Java: Aus Beliebigen Daten Binärdarstellung Erhalten - WinFuture-Forum.de

Zum Inhalt wechseln

Nachrichten zum Thema: Entwicklung
Seite 1 von 1

[erledigt] Java: Aus Beliebigen Daten Binärdarstellung Erhalten C-Programmierer sucht Java Hilfe


#1 _Fenix_

  • Gruppe: Gäste

geschrieben 09. Juli 2007 - 13:43

Hallo,
ich bin programmiere eigentlich hauptsächlich C, möchte aber diesmal ein Programm in Java schreiben, weil ich eine plattformunabhängige Soundlibrary brauche und die, die ich gefunden habe, alle nicht das gelbe vom Ei waren. Hoffe mein Problem ist nicht so trivial, dass ich mich lächerlich mache beim fragen.
Zum Problem:
Ich möchte gerne von beliebigen Daten eine Binäre Darstellung entsprechend des Speicherinhalts erhalten.
In C würde ich mein Problem wie folgt lösen:
char * get_binary(char * data_to_convert, size_t data_size) {
   
   unsigned long i; // Zählervariablen
   char j;
   
   char * output_buffer = (char*)calloc(8*data_size+1, sizeof(char)); // Ausgabepuffer (8 Bit pro Byte, 1 Byte zusätzlich, um String mit 0 abzuschließen

   for (i=0; i<data_size; i++) { // Für jedes Byte der Daten
	  char curbyte = data_to_convert[i];
	  for (j=1; j<9; j++) { // Für jedes Bit im aktuellen Byte
		 if ((curbyte ^ ((curbyte >> j) << j)) != 0) { // XOR mit dem nach links und rechts geschobenen Byte (alles rechts des aktuell interessanten Bits wird gelöscht)
			output_buffer[i*8+j-1] = 'T'; // Wenn XOR nicht 0 ergibt, dann soll T (True) im Rückgabestring stehen
	 } else {
			output_buffer[i*8+j-1] = 'F'; // Sonst F (false)
		 }
	 curbyte = (curbyte >> j) << j; // alles rechts vom aktuellen Bit im Byte killen
	 }
   }
   return output_buffer; // Rückgabestring auswerfen
}


Meine Frage: Wie mache ich das in Java? In C kann man ja jeden beliebigen Datentyp zu Char * bzw. zu Void * casten... nur in Java geht das soweit mir bekannt so nicht.
Hat jemand ne Idee?

Danke! :wink:

Dieser Beitrag wurde von Fenix bearbeitet: 03. August 2007 - 20:39

0

Anzeige



#2 Mitglied ist offline   MNG 

  • Gruppe: aktive Mitglieder
  • Beiträge: 288
  • Beigetreten: 29. März 06
  • Reputation: 0

geschrieben 09. Juli 2007 - 19:51

In Java ist das Ganze etwas schwieriger, weil man durch die VirtualMachine ja vom Speicher abstrahiert hat. Ich weiss jetzt leider nicht, was du mit den Daten vorhast, aber vielleicht hilft dir das weiter: Stichwort Serialisierung.
Damit kannst du jedes Objekt in eine byte-Sequenz verwandeln. Wie's geht, steht ganz grob hier:
http://www.uni-koeln.de/rrzk/kurse/unterla...erial/index.htm

Falls dir das nicht weiterhilft, beschreib mal, was du mit den Daten eigentlich vorhast. Vielleicht gibt es einen passenderen Ansatz.
0

#3 _Fenix_

  • Gruppe: Gäste

geschrieben 03. August 2007 - 20:39

So, danke für den Tipp. Habe es jetzt hinbekommen damit, geht super :-)
Im Anhang ist findet sich die Klasse, die beliebige Java Objekte in einen String mit Binärdarstellung wandelt (Dokumentiert und unter BSD-Lizenz :smokin: )

/*
* Copyright (c) 2007, Jan Bessai
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*	 * Redistributions of source code must retain the above copyright
*	   notice, this list of conditions and the following disclaimer.
*	 * Redistributions in binary form must reproduce the above copyright
*	   notice, this list of conditions and the following disclaimer in the
*	   documentation and/or other materials provided with the distribution.
*	 * Neither the name of Jan Bessai nor the
*	   names of its contributors may be used to endorse or promote products
*	   derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Jan Bessai ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Jan Bessai BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// This class provides the binary representation of any serializable Object in a String
// Diese Klasse liefert die Binäre Darstellung von jedem serialisierbaren Objekt als String

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.ClassNotFoundException;

final class BinaryRepresentation {
	
	private BinaryRepresentation() { }
	
	static String get_BinaryString(Object Object_to_convert, char char_for_one, char char_for_zero) throws IOException {
		String binarystring = new String(); // Resultvariable
		
		ObjectOutputStream ostream; // Stream to serialize data
		ByteArrayOutputStream byteostream; // Stream holding serialized bytes
		byte [] byteo; // Byte array, that will hold the contents of the stream
		
		byteostream = new ByteArrayOutputStream();
			
		ostream = new ObjectOutputStream(byteostream); // Initialize Streams and serialize Object into bytestream
		ostream.writeObject(Object_to_convert);
		ostream.close(); // close ostream, as no longer needed
			
		byteo = byteostream.toByteArray(); // get the serialized bytes
		byteostream.close(); // close byte output stream, as no longer needed
			
		for (int i = 0; i < byteo.length; i++) { // for each byte
			byte curbyte = byteo[i]; // store the byte
			for (int j = 1; j < 9; j++) { // for each bit in the current byte
				if ((curbyte ^ ((curbyte >> j) << j)) == 0) { // xor with right and left shifted byte, deletes everything but the currently interesting bit
					binarystring += char_for_zero; // if nothing remains add a zero representation to the outputstring
				} else {
					binarystring += char_for_one; // else add a one
				}
				curbyte = (byte)((curbyte >> j) << j); // remove processed bits
			}
		}
		
		return binarystring;
	}
	
	static Object get_Object(String String_to_convert, char char_for_one) throws IOException, ClassNotFoundException {
		Object convertedobject; // Resultvariable
		
		byte [] bytei = new byte [String_to_convert.length() / 8]; // Byte array, that will store the bytes from the String
		
		for (int i = 0; i < String_to_convert.length(); i++) { // Copy the bits from the String into the byte array ("trivial" math...)
			if (String_to_convert.charAt(i) == char_for_one) {
				bytei[(i / 8)] = (byte)(bytei[(i / 8)] + java.lang.Math.pow(2, (i%8)));
			}
		}
		
		ObjectInputStream istream; // De-serialization Stream to get the Object
		ByteArrayInputStream byteistream; // Stream to store the byte array
		
		byteistream = new ByteArrayInputStream(bytei); // Store the byte array
		istream = new ObjectInputStream(byteistream); // De-Serialize the data
		convertedobject = istream.readObject(); // Store the De-Serialized Object
		istream.close();
		byteistream.close();
				
		return convertedobject;
	}
	
	
}


Verwendungsbeispiel:
Integer test = new Integer(12345);
		
System.out.println("Object to convert: " + test);
		
try {
	String BinaryString = BinaryRepresentation.get_BinaryString(test, 'T', 'F');
	System.out.println("Converted Object: " + BinaryString);
	System.out.println("Converted Object length: " + BinaryString.length());
		
	Integer ReconvertedObject = (Integer)BinaryRepresentation.get_Object(BinaryString, 'T');
	System.out.println("Reconverted Object: " + ReconvertedObject);
} catch (Exception any) {
	System.out.println(any.getLocalizedMessage());
}


Bei Fragen dazu helfe ich gerne! Viel Spaß und danke nochmal ;)

Dieser Beitrag wurde von Fenix bearbeitet: 16. August 2007 - 01:17

0

#4 Mitglied ist offline   Cobinja 

  • Gruppe: Mitglieder
  • Beiträge: 8
  • Beigetreten: 29. September 06
  • Reputation: 0
  • Geschlecht:Männlich

geschrieben 05. August 2007 - 08:54

Ich hätte noch eine Kleinigkeit.

Du schreibst oben, dass du eigentlich mit C/C++ arbeitest. Deswegen sei es dir ausnahmsweise verziehen. Aber benutze in Java doch bitte für Klassennamen Großschreibung und für Objekte Kleinschreibung:

  BeispielKlasse beispielObjekt = new BeispielKlasse();


Es ist zwar nicht schriftlich als Standard definiert, hat sich aber bei Java-Entwicklern so durchgesetzt, um schon an der Schreibweise erkennen zu können, ob eine Klasse oder ein Objekt gemeint ist.

Dieser Beitrag wurde von Cobinja bearbeitet: 05. August 2007 - 08:54

0

#5 _Fenix_

  • Gruppe: Gäste

geschrieben 05. August 2007 - 18:34

Wurde verbessert, danke für den Hinweis. ^_^

Irgendwie isses ja eh blöd, dass man diese 2 Funktionen in eine extra Klasse einbaut. Schließlich braucht man dabei nicht so wirklich die Vorteile von ner Klasse.

Und ja ich weiß, das mit dem Error Ausgeben ist auch nicht 100% sauber; aber für mich tuts das. Wer mehr will, kann ja gerne mehr einbauen.


EDIT:
Habe die Klasse jetzt nochmal überarbeitet und nun sollte sie als Singleton ordentlich und sauber sein .. inklusive Fehlerrückgabe.

Dieser Beitrag wurde von Fenix bearbeitet: 16. August 2007 - 01:19

0

Thema verteilen:


Seite 1 von 1

1 Besucher lesen dieses Thema
Mitglieder: 0, Gäste: 1, unsichtbare Mitglieder: 0