The following method should swap the high nibble in a byte with the low nibble in a byte.

The following code dosn't work if the lower nibble is above 0111
if it is it returns a negative number...

Does anyone know what im doing wrong ?

public static void main(String[] args){
		byte inByte = (byte)0x09;
		byte out;
	    int by1 = (inByte >> 0) & 0x0f;
	    int by2 = (inByte >> 4) & 0x0f;
	    System.out.println(by1);
	    System.out.println(by2);
	    out = (byte)((by1 << 4 | by2 << 0) & 0xff);
		System.out.println(out);
	}

Thanks for your help,

Paul

This is how it ended up, My problem was basicly that bytes in java are signed bytes and the signed bit is the last bit...

Example:
10010100 - Signed Bit on neg number

01001001 - Signed bit off positive number.

This can be resolved by using the byte as an int when its needed
byte a = 0xFF
int b

b = a, should do the trick... I think casting will keep the sign (not what i want )..

// My new nibble swap

private static byte nibbleSwap(byte inByte){
		    int nibble0 = (inByte << 4) & 0xf0;
		    int nibble1 = (inByte >>> 4) & 0x0f;
		    return (byte)((nibble0 | nibble1));
	}

in java are signed bytes and the signed bit is the last bit...

The signed bit is the first bit, the leftmost bit.

1001 0000 0000 0000 0000 0000 0000 0000

The signed bit is a 1. -- negative


I think you got it, you just said the wrong thing!

Example:
10010100 - Signed Bit on neg number

01001001 - Signed bit off positive number.

Thats the leftmost number :P, or if your counting, the last bit... highest bit.. I guess would be a more approprate term

Thats the leftmost number :P, or if your counting, the last bit... highest bit.. I guess would be a more approprate term

I see where your coming from. I guess it doesn't matter how you look at it, as long as you get it.

public static void main(String[] args){
    byte inByte = (byte)0x09;
    byte out;
    int by1 = (inByte & 0x0f) >> 0 ;
    int by2 = (inByte  & 0x0f)>> 4; // <--
    System.out.println(by1);
    System.out.println(by2);
    out = (byte)((by1 << 4 | by2 << 0) & 0xff);
    System.out.println(out);
}

Try this one.
Regards

commented: *swing* and a miss!!! 4 years too LATE and no code tags. Though you did manage to find a wax crayon to colour it in. Good job -6

Try this one....
Regards
.................

Congratualtions,
The oldest thread reviving I have ever seen. Not to mention all the forum rules that you've just broken. (We do not give away free homework and we use code tags)
Last post by server_crash was May 8th, 2005 14:16.
What were you thinking? :)

commented: Just another noob who's discovered their first programming "fact" and is rushing madly around looking for someone to tell like it's the most important thing in the world. +29
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.