Matthew Conlisk
Matthew Conlisk

Reputation: 1

reverse hex 0x in javascript

I am playing with code code to make sprites. I have a right facing sprite and have been manually creating a left facing sprite. I am looking for a way to reverse a hex 0x to make the sprite face left. one line of the sprite is 0x01555500 and the reverse of that is 0x05555400. Does anyone know how I can do this using JavaScript?

Example:

the array:

[
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00554000, 0x01555500, 0x02AFB000, 0x0BBFBF00,
    0x0BAFEFC0, 0x0AFFAA00, 0x00FFFC00, 0x029A8000,
    0x0A9A6A00, 0x2A956A80, 0x3E75DBC0, 0x3F555FC0,
    0x3D5557C0, 0x01505400, 0x0A802A00, 0x2A802A80
]

and the reverse would be:

[
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0x00155000, 0x05555400, 0x00EFA800, 0x0FEFEE00,
    0x3FBFAE00, 0x0AAFFA00, 0x03FFF000, 0x002A6800,
    0x0A9A6A00, 0x2A956A80, 0x3E75DBC0, 0x3F555FC0,
    0x3D5557C0, 0x01505400, 0x0A802A00, 0x2A802A80
]

Upvotes: 0

Views: 658

Answers (1)

trincot
trincot

Reputation: 350961

You could use this:

function reverse(line) {
    line2 = 0;
    for (var i = 0; i < 31; i++) {
        line2 = (line2 << 1) | (line & 1)
        line >>= 1;
    }
    return line2;
}

function reverse(line) {
    line2 = 0;
    for (var i = 0; i < 31; i++) {
        line2 = (line2 << 1) | (line & 1)
        line >>= 1;
    }
    return line2;
}
// demo:
var line = 0x01555500;
var line2 = reverse(line);
console.log(('0000000' + line.toString(16)).slice(-8));
console.log(('0000000' + line2.toString(16)).slice(-8));

Upvotes: 2

Related Questions