Simple string / bytes problem
Hi
I'm basically trying to simulate DES in java from scratch (so no use of existing API's or anything). I've got a basic idea of how DES works (use of a feistel cipher).
So to start off I'm trying to get the bytes of a string with this simple program:
public class Test {
public static void main(String[] args) {
String testString = "hello";
System.out.println(testString.getBytes());
}The output consists of some characters (namely numbers, letters and 1 special character).
But when I change the variable testString to some other String, complie and run I still get the same output even though the String is different. Also why are there 9 characters for a String thats only 5 characters long?
Thanks
When you use System.out.println( something ) it uses to the toString() method of the object referenced by 'something'. When the something is an array such as an array of bytes the toString() methed returns a pseudo reference to the array which in no way reflects the content of the array.
If you just want to see the content of the array then use Arrays.toString(something) to generate a String representation of the content of the array.
Also, the use of String.getBytes() will convert the String to bytes using your default character encoding. This is rarely what you want since the result may depend on which platform you are working on. In my view, the safest and best approach is to explicitly define the encoding and since it will encode ALL characters one can throw at it I always use utf-8. So, to convert a String to bytes I would usebyte[] bytesOfString = "your string".getBytes("utf-8");and to convert them back to a String I would useString yourString = new String(bytesOfString,"utf-8");One final point, do not assume that an apparently random array of bytes such as one gets from DES encryption can be converted to a String using the above. In general it can't because not all bytes and byte sequences are valid for a particular character encoding. If you absolutely have to have a String representation then you should encode (not encrypt) the bytes using something like Base64 or Hex encoding.
Edited by: sabre150 on Jan 27, 2008 3:04 PM
Similar Messages
-
Simple String replacement problem
I want to replace every string of the type:
"^\\d+,[^,]+,,[^,]*,[^,]*$"
to:
"^\\d+,[^,]+,1,[^,]*,[^,]*$"
So that "1234,something,,something,something" becomes "1234,something,1,something,something"
What's the best way to do this?What are your EXACT requirements?
Do you want to replace all ,, with ,1, ?
Only a ,, that comes after number,something?
Right now, it looks like replaceFirst(",,", ",1,") will work. I doubt that's what you want, but there are probably a whole bunch of different regexes that could turn that input into that output. -
Base64Binary to byte[] problem in Wireless Toolkit and NetBeans
Hi,
I am generating stub with J2me Wireless toolkit. But the problem is that the toolkit can't successfully convert base64Binary to byte[] and gives error "Unknown simple type byte[]". Netbeans also gives some error while compiling it. Please anybody tell me how can i resolve this problem. Using base64Binary type is must.
Kindly reply if you know. My email address is [email protected]
Wasif Ehsan
[email protected]public interface JobUpdate {
@SuppressWarnings("unchecked")
public String[] getUpdatedJobList(@WebParam(name="phoneJobs")String[] phoneJobs);
@SuppressWarnings("unchecked")
public void retrieveJobsWorked(@WebParam(name="data")byte [] data);
I then use this to start the service
JobUpdateImpl implementor = new JobUpdateImpl();
JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();
svrFactory.setServiceClass(JobUpdate.class);
svrFactory.setAddress("http://localhost:9000/JobUpdate");
svrFactory.setServiceBean(implementor);
svrFactory.getInInterceptors().add(new LoggingInInterceptor());
svrFactory.getOutInterceptors().add(new LoggingOutInterceptor());
svrFactory.create();
Then use the wtk stub generator pointing at the service.
http://localhost:9000/JobUpdate?wsdl
The error returned by the tool is error: Found unknown simple type: byte[]
Any ideas? -
Hello everybody,
I'm in this situation: I have a byte array initialized by a list of integers. For some reason, my goal is to convert it to a String and then to get those integers.
I wrote this simple code:
byte b[] = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
String s = new String(b);
byte b2[] = s.getBytes();
for(int i=0; i<b2.length; i++)
System.out.println((int)(b2));
but, it works with all ingers except -127, in facts it displays -127 as 63!
How can I solve this problem? Thanks!BalusC wrote:
I tried ISO-8859-1 here and it worked.
byte[] bytes = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
String string = new String(bytes, "ISO-8859-1");
for (byte b : string.getBytes("ISO-8859-1")) {
System.out.print(b + " ");
All the ISOs 'work' but the point is - what it the OP trying to do? -
Memory leak in String(byte[] bytes, int offset, int length)
Has anyone run into memory leak problem using this String(byte[] bytes, int offset, int length) class? I am using it to convert byte array to string, and I am showing memory leak using this class. Any idea what is going on?
Hi,
If you post in Native methods forum I assume you are using this constructor in the native side.
Be aware that getting char * from jstring eats memory that you must free before returning from native with env->ReleaseStringUTFChars().
--Marc (http://jnative.sf.net) -
SIMPLE Database Design Problem !
Mapping is a big problem for many complex applications.
So what happens if we put all the tables into one table called ENTITY?
I have more than 300 attributeTypes.And there will be lots of null values in the records of that single table as every entityType uses the same table.
Other than wasting space if I put a clustered index on my entityType coloumn in that table.What kind of performance penalties to I get?
Definition of the table
ENTITY
EntityID > uniqueidentifier
EntityType > Tells the entityTypeName
Name >
LastName >
CompanyName > 300 attributeTypes
OppurtunityPeriod >
PS:There is also another table called RELATION that points the relations between entities.>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
check the coloumn with WHERE _entityType='PERSON'
as there is is clustered index on entityType...there
is NO performance decrease.
there is also a clustered index on RELATION table on
relationType
when we say WHERE _entityType ='PERSON' or
WHERE relationType='CONTACTMECHANISM'.
it scans the clustered index first.it acts like a
table as it is physically ordered.I was thinking in terms of using several conditions in the same select, such as
WHERE _entityType ='PERSON'
AND LastName LIKE 'A%' In your case you have to use at least two indices, and since your clustered index comes first ...
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Have you ever thought of using constraints in your
modell? How would you realize those?
...in fact we did.We have arranged the generic object
model in an object database.The knowledge information
is held in the object database.So your relational database is used only as a "simple" storage, everything has go through your object database.
But the data schema is held in the RDBMS with code
generation that creates a schema to hold data.If you think that this approach makes sense, why not.
But in able to have a efficent mapping and a good
performance we have thought about building only one
table.The problem is we know we are losing some space
but the thing is harddisk is much cheaper than RAM
and CPU.So our trade off concerated on the storage
cost.But I still wonder if there is a point that I
have missed in terms performance?Just test your approach by using sufficiently data - only you know how many records you have to store in your modell.
PS: it is not wise effective using generic object
models also in object databases as CPU cost is a lot
when u are holding the data.I don't know if I'd have taken your approach - using two database systems to hold data and business logic.
PS2: RDBMS is a value based system where object
databases are identity based.we are trying to be in
the gray area of both worlds.Like I wrote: if your approach works and scales to the required size, why not? I would assume that you did a load test with your approach.
What I would question though is that your discussing a "SIMPLE Database Design" problem. I don't see anything simple in your approach when it comes to implementation.
C. -
Simple String Compression Functions
Hi all !
I need two simple String compression functions, like
String compress(String what)
and
String decompress(String what)
myString.equals(decompress(compress(myString)))
should result in true.
Primarily I want to encode some plain text Strings so they are not too easy to read, and compression would be a nice feature here.
I already tried the util.zip package, but that one seems to need streams, I simply need Strings.
Any ideas ??
thx
SkippyIt does not do any compression, in fact it does
expansion to better encrypt the string (about 50%).How does that work? You want encryption to
decrease entropy.Why in the world do you say that, pjt33? What a very odd statement indeed. I sure hope you don't work in security, or I do hope you work in security if I'm a bad guy, or a competitor.
Let's say you had a 6-character string you wanted to encrypt.
Well, if you didn't increase the entropy, any 6-character plaintext string would have a 6-character encoded equivalent. And if you decreased entropy (e.g. coding the most commonly used words to shorter strings,) it gets even easier to decrypt.
Presumably there would be no hash collisions, after all, you want this to be reversible.
Hash collisions decrease entropy too, and, by doing so, make it easier to find a plaintext string that happens to hash to a certain value. This is a Bad Thing.
Now, to decode this, the Bad Guy only has to consider the set of 6-character strings and their hash values. You could even precalculate all of the common dictionary words, and everything with common letters and punctuation, making decryption virtually instantaneous. Especially if you had decreased the entropy in the signal, making fewer things I had to try.
But somebody who increased the entropy of their signal by adding random bits and increasing the encrypted size of the message to, say, 64 characters, would make it a lot harder to decrypt.
The ideal encryption system is pure noise; pure randomized entropy. An indecipherable wall of 0 and 1 seemingly generated at random. Statistical methods can't be used against it; nothing can be deciphered from it; it's as decipherable and meaningless as radio hiss. Now that's encryption! -
Hello All:
I need to write the following line into a file.
The line is: <?xml version="1.0" endcoding="UTF-8"?>
Below is the excerpt of my code:
BufferWriter bw = new BufferedWriter(new FileWriter("test.xml"));
String str = "<?xml version="1.0" endcoding="UTF-8"?>";
bw.write(str+System.getProperty("line.separator");
When I complie this Java code, I encountered the "; is expected" error because the compiler thought that the string ends at "<?xml version=".
Can anyone tell me how to solve this problem?
Thanks!Observe this:
String str = "<?xml version="1.0" endcoding="UTF-8"?>";
In this statement, the " is recognized as opening of string and closing of string. In this case, the string is ended like "<?xml version=", because its within the code. You might want to try something like:
String str = "<?xml version=\"1.0\" endcoding=\"UTF-8\"?>";
The \ character will make the subsequence characters in the string to be as a character in string, rather than a double quote to end the string until a " is met. -
A little byte[] problem
Hi,
I'm facing an unusual problem with creating an array of byte arrays, ie byte[][].
Below is my test code to create this array and read it back. For some reason this is not working. I'll definitely use some knowledge here. Thanks
import java.io.*;
public class Test {
static byte[][] testbyte = new byte[10][3];
public static void main(String[] args) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
for(int m=0;m<3;m++){
for (int i = 0; i < 10; i++) {
dout.writeInt(i*m);
testbyte[m]=bout.toByteArray();
for(int index=0;index<3;index++){
ByteArrayInputStream bin = new ByteArrayInputStream(testbyte[index]);
DataInputStream din = new DataInputStream(bin);
int m = 0;
while (m < 10) {
System.out.println(din.readInt());
m++;
catch (IOException ex) {
System.out.println(ex);
}Actually I send one row of data at a time - thatis
ony 8bytes * 4 = 32 bytes. If you are only send 4 doubles at a time, do you
need to keep all the previous values.
Sending 32 bytes every 10 ms should not be a
problem.
To do this I use DatagramPacket with an offset onthe byte array which
increments by 32 and a length of 32 bytes. If the byte array only contained the data you need to
send this would much simpler.
Note, toByteArray() creates a new byteArray copy of
the data in the ByteArrayOutputStream so it could be
copying around alot of data you don't need.I call toByteArray() only once. After the array is created I do something like DatagramPacket packet = new DatagramPacket(myByteArray,offset,length,address,port)
I'll try tcp as well though I anticipate the speedwill be much lower.
If you keep the socket connection open, then the
speed will be the same, except it will also be much
more reliable. Only the connection latency is slower.
However on a LAN this should less than 0.3 ms once
off.I'll definitely try this. Thanks for the headsup on the reason for the tcp latency. I though each send-receive transaction had to be ack'ed. -
Hi folks,-
i know this question might be very simple but i just cannot see what i am doing wrong here.
String stringA, stringB, stringC;
stringA= new String();
stringB= new String();
stringC= new String();
stringA = null;
stringB = "TRUE";
stringC = "Error:";
stringA.concat(stringB); // my code stops and quits here w/o error
// other codewhat is wrong here?
thanks muchcould you then please explain the following?
public String concat(String str)Concatenates the
specified string to the end of this string.
If the length of the argument string is 0, thenthis
String object is returned. Otherwise, a new String
object is created, representing a charactersequence
that is the concatenation of the charactersequence
represented by this String object and thecharacter
sequence represented by the argument string.
Examples:
"cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns"together"
Parameters:
tr - the String that is concatenated to the end of
this String.
Returns:
a string that represents the concatenation of this
object's characters followed by the stringargument's
characters.
Throws:
NullPointerException - if str is null.It returns a new String, which you are
throwing away. Change your code like this:
stringA = stringA.concat(stringB);
and then you'd get somewhere.yes, it makes sense but the description does not say this.
i think that will work but my problem is with the description of this
concat operation on the java web site.
thanks for the help -
The application in question uses JNI for legacy integration and I suspect the legacy code is corrupting the stack causing the above error. However, the error does not occur in Java 1.3, only Java 1.4.
Is there some way to suppress 1.4's use of the native IO API when encoding and decoding byte streams? This would at least provide a workaround in the meantime.
Thanks.This is beginning to make a little sense. The problem is that you got a String and you don't want one. A String wraps an array of chars, which your app needs, right? Specifically they're chars because you need 16-bit char sets.
Presumably the getBytes() method call is used to get an array of bytes for some data transfer operation. java.nio was probably added in 1.4 as it has some very efficient ways of handling buffers as simultaneously of two or more types. It's trying to use the underlying char array as a byte array and there's a straight up bug someplace.
Workaround is strange to contemplate, but I'm pretty sure it will work: use String.getChars() to get an array of chars, and then use java.nio yourself to create your byte array! If you've never been there, it's not very hard. I use nio all the time and it's never been a problem. -
Hello!
I'm trying to send data between to computer using RS232.
The problem I encounter is the following:
when I send data from 0 to 127 they are well received.
from 128 to 160 they are bad received (actually 130 is received as 8218, 131 as 405, 135 as 8225).
from 160 to 255 they are well received.
I know that bytes in Java are from -128 to +127 and I could understand that number greater than 127 have problems to be transmitted, but because of those 160 to 255 numbers that are well received, I don't get it.
I tried to find a pattern with the association of number sent and received between 128 and 160 but I didn't find anything relevant...
I'm using a simple RS232 cable via an USB to RS232 converter on my computer (I don't have any serial port) while the other computer is directly using its RS232 port.
The port is configured to send data to 9,6kbps, no parity bits, 1 stop bit and 8 data bits.
Has anyone any idea of where my problem could come from?
I get really confused with that...
By the way, if some admins wants to put my post somewhere else because here is not the appropriate place, I totally understand it but could he (or she?) just mail to tell me where it has been put, because last time I posted I didn't find it anymore... lol
Thanks ;)Please help me!
finally I cannot even write a conversion algorithm because different values return the same value (sounds odd but here it is:)
Send Receive
127 127
128 8364
129 65533
130 8218
131 402
132 8222
133 8230
134 8224
135 8225
136 710
137 8240
138 352
139 8249
140 338
141 65533
142 381
143 65533
144 65533
145 8216
146 8217
147 8220
148 8221
149 8226
150 8211
151 8212
152 732
153 8482
154 353
155 8250
156 339
157 65533
158 382
159 376
160 160
As you can see for example 143 and 144 both return 65533...
What can I do? -
Simple DataGrid validation Problem
hi friends
I am working on a application in which i m facing a problem.i have a datagrid having two column field one is simple datagrid column and in other datagrid column i render textinput as a component. there are only two row in my datagrid.so now i have to apply validation on that data grid.i mean if any textinput componet which is render in second column in data grid left blank and i click on save button then there should be validation Alert messg.
i am facing a problem on gettin id(instance) of that two rendered textinput component.Please help me out.
Thanks and Regards
Vineet OshoHi Vineet Osho,
You can try this...
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
>
<mx:Script>
<![CDATA[
import mx.utils.StringUtil;
import mx.collections.ArrayCollection;
import mx.controls.TextInput;
import mx.events.DataGridEvent;
import mx.controls.Alert;
public var arr:Array = [];
public var incrementer:int;
private function validateTextInputs():void
var strIndexes:String="";
var gridDP:ArrayCollection = dataGrid.dataProvider as ArrayCollection;
for(var i:int=0;i<gridDP.length;i++)
if(StringUtil.trim(gridDP.getItemAt(i).displayText) == "")
strIndexes += (i + 1) + ",";
if(strIndexes.length > 0)
strIndexes = strIndexes.substring(0,strIndexes.length-1);
Alert.show("The TextInputs " + strIndexes + " are empty.");
]]>
</mx:Script>
<mx:DataGrid id="dataGrid" horizontalCenter="0" verticalCenter="0" width="400" height="200">
<mx:columns>
<mx:DataGridColumn headerText="First" width="60" dataField="artist" editable="false"/>
<mx:DataGridColumn width = "60" headerText = "Premium %(e.g. Percentage as 100)" >
<mx:itemRenderer>
<mx:Component>
<mx:TextInput styleName="TextInputRight" focusOut="data.displayText=this.text;" width="100" text="{data.displayText}">
</mx:TextInput>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
<mx:dataProvider>
<mx:ArrayCollection>
<mx:Array>
<mx:Object title="Stairway to Heaven" artist="Led Zepplin" displayText=""/>
<mx:Object title="How to Save a Life" artist="Fray" displayText=""/>
</mx:Array>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:DataGrid>
<mx:Button id="btn" label="click" x="527" y="450" click="validateTextInputs()" />
</mx:Application>
Thanks,
Bhasker -
Simple Mobile Bookshop problem
Hello,
I have to write some simple program using choicegroups, textfields, forms and other basic elements. I's kind of bookshop, I have written almost everything, but I have huge problem with displaying basket.
this is the code for whole my app [ if anybody want to run it, just delete the lines with images ]
[http://www.iie.org.pl/book.java]
u see, there are 5 categories of books [ and five ChoiceGroups for them ], user can choose couple of books from different categories, and he/she get the price, this is working just fine, the problem is to display them, I've try to move choosen to separate array, but it can hold just 5 values [ ( no, I can't make it larger ) check the code [ public int checker () ]]. To be honest I don't know how to move it on, try different things [ ignore the last two methods, just for testing reasons ], but without success. Can You just focus on this basket and not making comments about the rest of the code [ I know its messy ]. This is my first larger progam for mobiles.OK, this will add the books in the array:
public int checker( ChoiceGroup chg, int temp[], Form fr){
String message="";
boolean arra [] = new boolean[chg.size()];
chg.getSelectedFlags(arra);
for (int i = 0; i < arra.length; i++) {
if (arra) {
//this will add the books in the array books[]
books[co] = chg.getString(i);
//checking the array
System.out.println(books[co]+" co = "+co);
co += 1;
fsuma = temp[i]+ fsuma;
message = "" + fsuma ;
//bask_help(chg.getString(i));
}Edited by: Sypress on Mar 15, 2010 2:11 AM -
Simple project,serious problem
my flex mobile project for android is so simple that it just outputs a string "hello world",but i get serious problem on many android devices when launch it after successfully installed while some devices work well.can anybody explain why?i use FB4.6+air3.3.
Hi
Easy answer is - No not with standard iMovie any version (with plug-ins and
iMovie prior to iM '08 or 09 - may be)
Suggested one - Yes but You don't need pro version Express will do it as nicely.
I think it also can be done with QuickTime-pro.
I would use FinalCut Express and import the movie here and re-size.
If only a DVD copy I would either
• copy back to a new miniDV tape (via a DVD-Player and Camera) - or -
• use Roxio Toast™ and back convert to streamingDV
then use this in FCE
Yours Bengt W
Maybe you are looking for
-
Using Messages with Multiple Users and Multiple Computers
I have two users who share two different computers, switching between them during the day. I'd like to use messages on them for us to send text messages in the office, however, it asks them on logging in (most, but not everytime) to re-enter their ap
-
IPv6 Usage on The Verizon Cellular Network
Hi, I'm trying to create an application that connects from a host to a mobile Android phone on the Verizon cellular network. This device uses only the 3G network and has its Wi-Fi turned off. The Android device has a listening socket. As far as I kno
-
Hello, I just entered metalink to download some patches to update my database (I have 11.1.0.7.0). I found an patch set to update to 11.1.0.7.4 at least and want to install it. When I need to choose for which platform to download it to I cannot find
-
Auto save a copy of outgoing email in SharePoint 2010
Hi, I need to save a copy of an outgoing email from SharePoint Server 2010. So is there any option in SharePoint to save a copy as audit or do we need to write custom thing for this? Any idea how to achieve this . pls share your thougths if you do
-
How to omprove performance my program?
Procedure xyz() Cursor C1 Very largequery handling some bulk data. Cursor C2 Very largequery handling some bulk data. Cursor C3 Very largequery handling some bulk data. Cursor C4 Very largequery handling some bulk data. Cursor C5 Very largequery hand