How to convert a (short) sample to a sound file in an array of bytes

When converting from short to byte array, I found the following solution on the Internet, but could not understand what this logic consists of.

//buffer is an array of bytes, bytes[]
buffer[position] = (byte)(sample & 0xff);
buffer[position+1] = (byte)((sample >> 8) & 0xff);

Can someone tell me why 0xff (256) is being sent to a sample that is short?

+3
source share
4 answers

This code probably comes from C code (or was written by a C programmer who does not parse Java, as well as erickson). This is due to the fact that in Java casting from a type with more information to a type with less information discards bits of a higher order, and therefore in both cases 0xff is not required.

16 , . , , , .

, , ,

1110001100001111 sample
0000000011111111 0xff
0000000000001111 sample & 0xff => first byte`

,

0000000011100011 sample >> 8
0000000011111111 0xff
0000000011100011 (sample >> 8 ) & 0xff => second byte

, erickson (, ).

+12

, , , -.

& 0xFF .

, . , & 0xFF short int 24 , , . . Java §5.1.3.

buffer[position] = (byte) sample;
buffer[position+1] = (byte) (sample >>> 8);

, , . , , . , , , , .

+2

, ; , LSByte "sample" OUT 8 , 0-255; MSByte "sample" ( ) . , 8 8 , .

, , (2 ), 256-6553 255 .

+1
buffer[position] = (byte)(sample & 0xff);
buffer[position+1] = (byte)((sample >> 8) & 0xff);

:

buffer[position] = (byte)((sample >> 8) & 0xff);
buffer[position+1] = (byte)(sample & 0xff);
+1

Source: https://habr.com/ru/post/1699292/


All Articles