Преобразуйте Байты вдребезги

Вы можете использовать Counter и defaultdict в модуле Python 2.7 collections в два этапа. Сначала используйте Counter, чтобы создать словарь, в котором каждое слово является ключом с соответствующим счетчиком частоты. Это довольно тривиально.

Во-вторых, defaultdict можно использовать для создания перевернутого или обращенного словаря, где ключи - это частота встречаемости, а связанные значения - это списки слова или слов, которые встречались столько раз. Вот что я имею в виду:

from collections import Counter, defaultdict

wordlist = ['red', 'yellow', 'blue', 'red', 'green', 'blue', 'blue', 'yellow']

# invert a temporary Counter(wordlist) dictionary so keys are
# frequency of occurrence and values are lists the words encountered
freqword = defaultdict(list)
for word, freq in Counter(wordlist).items():
    freqword[freq].append(word)

# print in order of occurrence (with sorted list of words)
for freq in sorted(freqword):
    print('count {}: {}'.format(freq, sorted(freqword[freq])))

Вывод:

count 1: ['green']
count 2: ['red', 'yellow']
count 3: ['blue']
5
задан bignose 13 June 2009 в 02:22
поделиться

6 ответов

Я не разработчик Java, так что это может быть совершенно нестандартно, но рассматривали ли вы возможность использования ByteBuffer ?

7
ответ дан 13 December 2019 в 22:15
поделиться

Предположим, что младший бит находится в данных [0]

int val;

val = (((int)data[0]) & 0x00FF) | ((int)data[1]<<8);
4
ответ дан 13 December 2019 в 22:15
поделиться

Как предлагалось ранее, в Java есть классы, которые помогут вам в этом. Вы можете обернуть свой массив в ByteBuffer , а затем получить его представление IntBuffer .

ByteBuffer bb = ByteBuffer.wrap(audioData);
// optional: bb.order(ByteOrder.BIG_ENDIAN) or bb.order(ByteOrder.LITTLE_ENDIAN)
IntBuffer ib = bb.asIntBuffer();
int firstInt = ib.get(0);
1
ответ дан 13 December 2019 в 22:15
поделиться

Вы можете преобразовать на короткий (2 байта) путем логического ИЛИ двух байтов вместе:

short value = ((short) audioData[0]) | ((short) audioData[1] << 8);
0
ответ дан 13 December 2019 в 22:15
поделиться

Предлагаю вам взглянуть на Преон . В Preon можно было бы сказать что-то вроде этого:

class Sample {

  @BoundNumber(size="16") // Size of the sample in bits
  int value;

}

class AudioFile {

  @BoundList(size="...") // Number of samples
  Sample[] samples;

}

byte[] buffer = ...;
Codec<AudioFile> codec = Codecs.create(AudioFile.class);
AudioFile audioFile = codec.decode(buffer);
0
ответ дан 13 December 2019 в 22:15
поделиться
ByteInputStream b = new ByteInputStream(audioData);
DataInputStream data = new DataInputStream(b);
short value = data.readShort();

The advantage of the above code is that you can keep reading the rest of 'data' in the same way.

A simpler solution for just two values might be:

short value = (short) ((audioData[0]<<8) | (audioData[1] & 0xff));

This simple solution extracts two bytes, and pieces them together with the first byte being the higher order bits and the second byte the lower order bits (this is known as Big-Endian; if your byte array contained Little-Endian data, you would shift the second byte over instead for 16-bit numbers; for Little-Endian 32-bit numbers, you would have to reverse the order of all 4 bytes, because Java's integers follow Big-Endian ordering).

1
ответ дан 13 December 2019 в 22:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: