3

In function is transmited double.

function writebyte(id, data)
{
    data = Math.floor(data);
    buf[id] = String.fromCharCode(data & (255));
}

It works ok for 0-127 values. But with negative or > 127 works wrong.

128 = 0xC2 0x80 (should be 0x80 1 byte)
-1  = 0xC3 0xBF (should be 0xFF 1 byte)

So I think problem is function String.fromCharCode with parameter 128++ or negative.

Is there any way writing bytes to array directly without String.fromCharCode?

6
  • 2
    It looks like you are wanting to be able to represent numbers greater than +127 with 8 bits yet also represent negative numbers with twos complement binary with the MSB acting as -128. You can't do both... Commented Dec 6, 2011 at 13:46
  • I dont understand. Why cant I do both? -1 == 255 == 0xFF -2 == 254 == 0xFE. buf is sent by websocket protocol i just want that if i transmit -1 or 255 to this function first byte would be 0xFF (for example) Commented Dec 6, 2011 at 14:04
  • 128 == 0x80. There no -128 (max signed is -127) Commented Dec 6, 2011 at 14:12
  • 1
    Well conventionally the most-significant bit is made negative (ie -128) giving a range of -128 to 127 for a signed bit. I'm not sure if you are using a different system? Commented Dec 6, 2011 at 14:16
  • You are right. So signed range -128 to 127. Unsigned 0 to 255. But this doesnt solve my question. I want transmit in function -1 and in data[id] should be 0xFF or I transmit 255 and in data[id] should 0xFF and so on. Commented Dec 6, 2011 at 14:21

1 Answer 1

1

In this answer you will find JavaScript code that will convert from (hex) bytes into a double. [JS doesn't have "floats"]

Reversing the process is left as an exercise for the reader...

Sign up to request clarification or add additional context in comments.

7 Comments

-1; Byte operations in JS convert the double to an intermediate integer representation. They do not operate on the actual floating point representation.
@missingno you're missing the point - by manipulation of the original floating point number it is possible to calculate the sign, mantissa, and exponent, and from there work out the correct IEE754 representation thereof. The code I previously posted does that in reverse.
Doesnt Math.floor convert float to integer?
@Demion no, not really, it just removes the fractional component. In any event, can you clarify your question - it now appears that you're really only talking about small integer values, and not doubles at all!
Yes i work only with -128 .. 127 or with 0..255. But another (not mine) code transmits double to this function.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.