Question regarding StringUtils.bytesToHex()

Hi guys,

I’m trying to reduce the length of IDs to 8 characters in J2ME. From what i see in J2SE, it works perfectly fine doin this way
myID = StringUtils.bytesToHex(userID, [color=red]userID.length - 4); [/color]

however in J2ME, it didn’t work that way. :-\

Hi,

Mmm. I cant seem to find the class StringUtils and the method bytesToHex in the JDK docs.

If I look at your code I think you’re converting a byte/char array into a hexadecimal string minus
the last 4 bytes/chars. One byte/char would correspond to 2 digits in the resulting string.

So limiting the length to 8 would only work if the original userId would be exactly 8 bytes
-> abcdefgh minus 4 -> abcd -> 61626364
If it would be, lets say 6 bytes the result would be :
-> abcdef minus 4 -> ab -> 6162
Oops :slight_smile:

If you would want to limit the length of an array why not use System.arraycopy :


        char[] src="42:life universe everything".toCharArray();
        char[] dst=new char[8];
        System.arraycopy(src,0,dst,0,dst.length);
        myId=new String(dst);

or…


       myId=new String(userId,0,userId.length>8?8:userId.length);

Good luck !

Erik

wow, it works using this,
myId=new String(userId,0,userId.length>8?8:userId.length);
thanks!! ;D

but could you roughly explain to me the meaning of this line?
userId.length>8?8:userId.length

?:

so…

int y=x<0?-x:x;

would be similar to:

int y=(int)Math.abs(x);

or:

int y;
if(x<0)
y=-x;
else
y=x;

You should probably replace “do this” with “the value of this”. Otherwise it sounds like ?: is a flow control statement.


userId.length>8?8:userId.length;

Is the exact same (if you are using ints, which you are) to:

Math.max(user.length, 8);

The only difference is that the 2nd version is more verbose and it does some funky stuff with NaN and negative zeros in float and doubles…

DP

It’s not equal…

you can do:


if(var)
   doThis();
else
   doThat();

But you can’t do:


(var ? doThis() : doThat());

Only when both methods return the same type (and not void):


result = (var ? doThis() : doThat());

yes, but we are talking about array.length which is of type int…there is no problem with methods in this case.

But yes, you are right, both methods need to return the same type and not void obviously.

DP

icic…, thanks for all the explanation. really appreciate it! :wink: