How to create a 32-bit integer from eight (8) 4-bit integers? The Next CEO of Stack OverflowSeeding the random number generator in JavascriptCreate GUID / UUID in JavaScript?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?

Rotate a column

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

How to be diplomatic in refusing to write code that breaches the privacy of our users

Why did we only see the N-1 starfighters in one film?

Why does standard notation not preserve intervals (visually)

What does "Its cash flow is deeply negative" mean?

Customer Requests (Sometimes) Drive Me Bonkers!

Return the Closest Prime Number

Is HostGator storing my password in plaintext?

Grabbing quick drinks

How do spells that require an ability check vs. the caster's spell save DC work?

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

What is the difference between "behavior" and "behaviour"?

What's the point of interval inversion?

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

How to use tikz in fbox?

The King's new dress

Unreliable Magic - Is it worth it?

Why here is plural "We went to the movies last night."

Opposite of a diet

How do scammers retract money, while you can’t?

WOW air has ceased operation, can I get my tickets refunded?

What can we do to stop prior company from asking us questions?

Does the Brexit deal have to be agreed by both Houses?



How to create a 32-bit integer from eight (8) 4-bit integers?



The Next CEO of Stack OverflowSeeding the random number generator in JavascriptCreate GUID / UUID in JavaScript?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?










14















Let's say I have a max 32-bit integer -






const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





So far so good. But now let's say I want to make a 32-bit number using eight (8) 4-bit numbers. The idea is simple: shift (<<) each 4-bit sequence into position and add (+) them together -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





I'm getting -1 but the expected result is 32-bits of all ones, or 11111111111111111111111111111111.



Worse, if I start with the expected outcome and work my way backwards, I get the expected result -






const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





I tried debugging my make function to ensure there wasn't an obvious problem -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





The formula looks like it checks out. I thought maybe it was something to do with + and switched to bitwise or (|) which should effectively do the same thing here -






const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





However, I get the same bug with my make function when attempting to combine all eight (8) numbers -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





What gives?



The goal is to convert eight (8) 4-bit integers into a single 32-bit integer using JavaScript - this is just my attempt. I'm curious where my function is breaking, but I'm open to alternative solutions.



I'd like to avoid converting each 4-bit integer to a binary string, mashing the binary strings together, then parsing the binary string into a single int. A numeric solution is preferred.










share|improve this question

















  • 1





    It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

    – user633183
    19 hours ago











  • Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

    – harold
    15 hours ago















14















Let's say I have a max 32-bit integer -






const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





So far so good. But now let's say I want to make a 32-bit number using eight (8) 4-bit numbers. The idea is simple: shift (<<) each 4-bit sequence into position and add (+) them together -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





I'm getting -1 but the expected result is 32-bits of all ones, or 11111111111111111111111111111111.



Worse, if I start with the expected outcome and work my way backwards, I get the expected result -






const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





I tried debugging my make function to ensure there wasn't an obvious problem -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





The formula looks like it checks out. I thought maybe it was something to do with + and switched to bitwise or (|) which should effectively do the same thing here -






const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





However, I get the same bug with my make function when attempting to combine all eight (8) numbers -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





What gives?



The goal is to convert eight (8) 4-bit integers into a single 32-bit integer using JavaScript - this is just my attempt. I'm curious where my function is breaking, but I'm open to alternative solutions.



I'd like to avoid converting each 4-bit integer to a binary string, mashing the binary strings together, then parsing the binary string into a single int. A numeric solution is preferred.










share|improve this question

















  • 1





    It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

    – user633183
    19 hours ago











  • Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

    – harold
    15 hours ago













14












14








14








Let's say I have a max 32-bit integer -






const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





So far so good. But now let's say I want to make a 32-bit number using eight (8) 4-bit numbers. The idea is simple: shift (<<) each 4-bit sequence into position and add (+) them together -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





I'm getting -1 but the expected result is 32-bits of all ones, or 11111111111111111111111111111111.



Worse, if I start with the expected outcome and work my way backwards, I get the expected result -






const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





I tried debugging my make function to ensure there wasn't an obvious problem -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





The formula looks like it checks out. I thought maybe it was something to do with + and switched to bitwise or (|) which should effectively do the same thing here -






const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





However, I get the same bug with my make function when attempting to combine all eight (8) numbers -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





What gives?



The goal is to convert eight (8) 4-bit integers into a single 32-bit integer using JavaScript - this is just my attempt. I'm curious where my function is breaking, but I'm open to alternative solutions.



I'd like to avoid converting each 4-bit integer to a binary string, mashing the binary strings together, then parsing the binary string into a single int. A numeric solution is preferred.










share|improve this question














Let's say I have a max 32-bit integer -






const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





So far so good. But now let's say I want to make a 32-bit number using eight (8) 4-bit numbers. The idea is simple: shift (<<) each 4-bit sequence into position and add (+) them together -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





I'm getting -1 but the expected result is 32-bits of all ones, or 11111111111111111111111111111111.



Worse, if I start with the expected outcome and work my way backwards, I get the expected result -






const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





I tried debugging my make function to ensure there wasn't an obvious problem -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





The formula looks like it checks out. I thought maybe it was something to do with + and switched to bitwise or (|) which should effectively do the same thing here -






const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





However, I get the same bug with my make function when attempting to combine all eight (8) numbers -






const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





What gives?



The goal is to convert eight (8) 4-bit integers into a single 32-bit integer using JavaScript - this is just my attempt. I'm curious where my function is breaking, but I'm open to alternative solutions.



I'd like to avoid converting each 4-bit integer to a binary string, mashing the binary strings together, then parsing the binary string into a single int. A numeric solution is preferred.






const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





const a =
((2 ** 32) - 1)

const b =
parseInt("11111111111111111111111111111111", 2) // 32 bits, each is a one!

console.log(a === b) // true

console.log(a.toString(2))
// 11111111111111111111111111111111 (32 ones)

console.log(b.toString(2))
// 11111111111111111111111111111111 (32 ones)





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) + make (more, e + 4)

const print = n =>
console.log(n.toString(2))

// 4 bits
print(make([ 15 ])) // 1111

// 8 bits
print(make([ 15, 15 ])) // 11111111

// 12 bits
print(make([ 15, 15, 15 ])) // 111111111111

// 16 bits
print(make([ 15, 15, 15, 15 ])) // 1111111111111111

// 20 bits
print(make([ 15, 15, 15, 15, 15 ])) // 11111111111111111111

// 24 bits
print(make([ 15, 15, 15, 15, 15, 15 ])) // 111111111111111111111111

// 28 bits
print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111

// almost there ... now 32 bits
print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





const c =
`11111111111111111111111111111111`

const d =
parseInt(c, 2)

console.log(d) // 4294967295

console.log(d.toString(2) === c) // true





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? `0`
: `($bit << $e) + ` + make (more, e + 4)

console.log(make([ 15, 15, 15, 15, 15, 15, 15, 15 ]))
// (15 << 0) + (15 << 4) + (15 << 8) + (15 << 12) + (15 << 16) + (15 << 20) + (15 << 24) + (15 << 28) + 0





const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





const a =
parseInt("1111",2)

const b =
(a << 0) | (a << 4)

console.log(b.toString(2)) // 11111111

const c =
b | (a << 8)

console.log(c.toString(2)) // 111111111111





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(





const make = ([ bit, ...more ], e = 0) =>
bit === undefined
? 0
: (bit << e) | make (more, e + 4)

const print = n =>
console.log(n.toString(2))


print(make([ 15, 15, 15, 15, 15, 15, 15 ])) // 1111111111111111111111111111 (28 bits)

print(make([ 15, 15, 15, 15, 15, 15, 15, 15 ])) // -1 :(






javascript twos-complement base-conversion






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 20 hours ago









user633183user633183

71.8k21143183




71.8k21143183







  • 1





    It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

    – user633183
    19 hours ago











  • Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

    – harold
    15 hours ago












  • 1





    It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

    – user633183
    19 hours ago











  • Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

    – harold
    15 hours ago







1




1





It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

– user633183
19 hours ago





It looks like bitwise operators says "The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32-bit signed number." Indeed (15 << 28) lies beyond this range, however JavaScript's MAX_SAFE_INTEGER supports up to 53 bits. Is there a safe and reliable way to use bitwise operators on larger-than-32-bit numbers?

– user633183
19 hours ago













Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

– harold
15 hours ago





Is the signedness really unacceptable? They're the same bits after all, just slightly a different interpretation

– harold
15 hours ago












1 Answer
1






active

oldest

votes


















13














The bitwise operators will result in a signed 32 bit number, meaning that if the bit at position 31 (counting from the least significant bit at the right, which is bit 0) is 1, the number will be negative.



To avoid this from happening, use other operators than << or |, which both result in a signed 32-bit number. For instance:



(bit * 2**e) + make (more, e + 4)


Forcing unsigned 32-bit



Bit shifting operators are designed to force the result into the signed 32-bit range, at least that is claimed on mdn (at the time of writing):




The operands of all bitwise operators are converted to signed 32-bit integers




This is in fact not entirely true. The >>> operator is an exception to this. EcmaScript 2015, section 12.5.8.1 states that the operands are mapped to unsigned 32 bit before shifting in the 0 bits. So even if you would shift zero bits, you'd see that effect.



You would only have to apply it once to the final value, like for instance in your print function:



console.log((n>>>0).toString(2))


BigInt solution



If you need even more than 32 bits, and your JavaScript engine supports BigInt like some already do, then use BigInts for the operands involved in the bitwise operators -- these will then not use the 32-bit signed number wrapping (notice the n suffixes):






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





NB: If you get an error running the above, try again with Chrome...






share|improve this answer

























  • bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

    – user633183
    19 hours ago












  • No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

    – user633183
    19 hours ago











  • I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

    – user633183
    19 hours ago












  • It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

    – trincot
    18 hours ago











  • that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

    – user633183
    8 hours ago











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390991%2fhow-to-create-a-32-bit-integer-from-eight-8-4-bit-integers%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









13














The bitwise operators will result in a signed 32 bit number, meaning that if the bit at position 31 (counting from the least significant bit at the right, which is bit 0) is 1, the number will be negative.



To avoid this from happening, use other operators than << or |, which both result in a signed 32-bit number. For instance:



(bit * 2**e) + make (more, e + 4)


Forcing unsigned 32-bit



Bit shifting operators are designed to force the result into the signed 32-bit range, at least that is claimed on mdn (at the time of writing):




The operands of all bitwise operators are converted to signed 32-bit integers




This is in fact not entirely true. The >>> operator is an exception to this. EcmaScript 2015, section 12.5.8.1 states that the operands are mapped to unsigned 32 bit before shifting in the 0 bits. So even if you would shift zero bits, you'd see that effect.



You would only have to apply it once to the final value, like for instance in your print function:



console.log((n>>>0).toString(2))


BigInt solution



If you need even more than 32 bits, and your JavaScript engine supports BigInt like some already do, then use BigInts for the operands involved in the bitwise operators -- these will then not use the 32-bit signed number wrapping (notice the n suffixes):






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





NB: If you get an error running the above, try again with Chrome...






share|improve this answer

























  • bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

    – user633183
    19 hours ago












  • No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

    – user633183
    19 hours ago











  • I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

    – user633183
    19 hours ago












  • It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

    – trincot
    18 hours ago











  • that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

    – user633183
    8 hours ago















13














The bitwise operators will result in a signed 32 bit number, meaning that if the bit at position 31 (counting from the least significant bit at the right, which is bit 0) is 1, the number will be negative.



To avoid this from happening, use other operators than << or |, which both result in a signed 32-bit number. For instance:



(bit * 2**e) + make (more, e + 4)


Forcing unsigned 32-bit



Bit shifting operators are designed to force the result into the signed 32-bit range, at least that is claimed on mdn (at the time of writing):




The operands of all bitwise operators are converted to signed 32-bit integers




This is in fact not entirely true. The >>> operator is an exception to this. EcmaScript 2015, section 12.5.8.1 states that the operands are mapped to unsigned 32 bit before shifting in the 0 bits. So even if you would shift zero bits, you'd see that effect.



You would only have to apply it once to the final value, like for instance in your print function:



console.log((n>>>0).toString(2))


BigInt solution



If you need even more than 32 bits, and your JavaScript engine supports BigInt like some already do, then use BigInts for the operands involved in the bitwise operators -- these will then not use the 32-bit signed number wrapping (notice the n suffixes):






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





NB: If you get an error running the above, try again with Chrome...






share|improve this answer

























  • bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

    – user633183
    19 hours ago












  • No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

    – user633183
    19 hours ago











  • I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

    – user633183
    19 hours ago












  • It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

    – trincot
    18 hours ago











  • that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

    – user633183
    8 hours ago













13












13








13







The bitwise operators will result in a signed 32 bit number, meaning that if the bit at position 31 (counting from the least significant bit at the right, which is bit 0) is 1, the number will be negative.



To avoid this from happening, use other operators than << or |, which both result in a signed 32-bit number. For instance:



(bit * 2**e) + make (more, e + 4)


Forcing unsigned 32-bit



Bit shifting operators are designed to force the result into the signed 32-bit range, at least that is claimed on mdn (at the time of writing):




The operands of all bitwise operators are converted to signed 32-bit integers




This is in fact not entirely true. The >>> operator is an exception to this. EcmaScript 2015, section 12.5.8.1 states that the operands are mapped to unsigned 32 bit before shifting in the 0 bits. So even if you would shift zero bits, you'd see that effect.



You would only have to apply it once to the final value, like for instance in your print function:



console.log((n>>>0).toString(2))


BigInt solution



If you need even more than 32 bits, and your JavaScript engine supports BigInt like some already do, then use BigInts for the operands involved in the bitwise operators -- these will then not use the 32-bit signed number wrapping (notice the n suffixes):






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





NB: If you get an error running the above, try again with Chrome...






share|improve this answer















The bitwise operators will result in a signed 32 bit number, meaning that if the bit at position 31 (counting from the least significant bit at the right, which is bit 0) is 1, the number will be negative.



To avoid this from happening, use other operators than << or |, which both result in a signed 32-bit number. For instance:



(bit * 2**e) + make (more, e + 4)


Forcing unsigned 32-bit



Bit shifting operators are designed to force the result into the signed 32-bit range, at least that is claimed on mdn (at the time of writing):




The operands of all bitwise operators are converted to signed 32-bit integers




This is in fact not entirely true. The >>> operator is an exception to this. EcmaScript 2015, section 12.5.8.1 states that the operands are mapped to unsigned 32 bit before shifting in the 0 bits. So even if you would shift zero bits, you'd see that effect.



You would only have to apply it once to the final value, like for instance in your print function:



console.log((n>>>0).toString(2))


BigInt solution



If you need even more than 32 bits, and your JavaScript engine supports BigInt like some already do, then use BigInts for the operands involved in the bitwise operators -- these will then not use the 32-bit signed number wrapping (notice the n suffixes):






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





NB: If you get an error running the above, try again with Chrome...






const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...





const make = ([ bit, ...more ], e = 0n) =>
bit === undefined
? 0n
: (bit << e) + make (more, e + 4n)

const print = n =>
console.log(n.toString(2))

// Test
for (let i=1; i<20; i++)
print(make(Array(i).fill(15n))) // longer and longer array...






share|improve this answer














share|improve this answer



share|improve this answer








edited 7 hours ago

























answered 19 hours ago









trincottrincot

130k1691125




130k1691125












  • bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

    – user633183
    19 hours ago












  • No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

    – user633183
    19 hours ago











  • I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

    – user633183
    19 hours ago












  • It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

    – trincot
    18 hours ago











  • that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

    – user633183
    8 hours ago

















  • bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

    – user633183
    19 hours ago












  • No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

    – user633183
    19 hours ago











  • I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

    – user633183
    19 hours ago












  • It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

    – trincot
    18 hours ago











  • that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

    – user633183
    8 hours ago
















bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

– user633183
19 hours ago






bit is a bit of a misnomer here. Can you actually multiply the 4-bits directly by the exponent there? Typically the base conversion is done using bit0 * 2**0 + bit1 * 2**1 + bit2 * 2**2 + bit3 * 2**3, etc. I'm thinking I would have to break the 4-bit segments into individual bits and multiply each one by the increasing exponents.

– user633183
19 hours ago














No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

– user633183
19 hours ago





No point in guessing, I tried it an it works just fine. Thanks @trincot. I learned a useful shortcut in base conversion today!

– user633183
19 hours ago













I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

– user633183
19 hours ago






I never felt a "shortcoming" in JavaScript's bitwise operators before today. Is it even reasonable to expect a new set of bitwise operators that works in the 64-bit space?

– user633183
19 hours ago














It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

– trincot
18 hours ago





It is not really a shortcoming, but intended. I have added a new section to my answer which may interest you.

– trincot
18 hours ago













that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

– user633183
8 hours ago





that's great. I didn't know BigInt support was already here. The new section makes perfect sense.

– user633183
8 hours ago



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390991%2fhow-to-create-a-32-bit-integer-from-eight-8-4-bit-integers%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020