Abu Bakar
Abu Bakar

Reputation: 185

Convert Hexadecimal C Array to Matlab Vector

I am looking for a simple way to convert from c-code hex array to matlab

Available C-Code Format: const uint16_t AUDIO_SAMPLE[] = {0x4952, 0x4646, 0x4f6e, 0xf, 0x4157, 0x4556, 0x6d66, 0x2074, 0x12, 0, 0x1}

Required Matlab Format: AUDIO_SAMPLE = [18770 17990 20334 15 16727 17750 28006 8308 18 0 1]

Though it is simple to convert for small numbers, I have to convert a very big array. I am using embedded platform so the numbers can not be written to a simple text file for later read in matlab. Its preferable to write the conversion code in matlab.

Edit:

Till now able to get rid of 0x. Failed to get a vector after using eval function as given below:

a='0x4952, 0x4646, 0x4f6e'; %Given
b = strrep(a, '0x', '') ; %Returns 4952, 4646, 4f6e
x = eval( [ '[', b, ']' ] ) %

Upvotes: 1

Views: 323

Answers (2)

Abu Bakar
Abu Bakar

Reputation: 185

It proved tougher than I thought.

Contents of the text file audio.c

4952, 4646, 0x4f6e, 0xf, 0x4157, 0x4556, 0x6d66, 0x2074, 0x12, 0, 0x1, 
0x2, 0xbb80, 0, 0xee00, 0x2, 0x4, 0x10, 0, 0x6166, 0x7463, 0x4, 
0, 0xd3cf, 0x3, 0x6164, 0x6174, 0x4f3c, 0xf, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 

The given file has 11 values in each line. Here follows the MATLAB code to convert HEX values to decimal numbers:

fp = fopen('audio.c', 'rt');
C = textscan(fp, '%s', 'CommentStyle', '#', 'Delimiter', '');
fclose(fp);

C = regexp(C{:}, '\w+', 'match');
C = cellfun(@(x)strrep(x,'0x',''), C, 'UniformOutput', false);
C = cellfun(@(x)hex2dec(x), C, 'UniformOutput', false);
result=cell2mat(C)'
allOneString = sprintf('%d, ' , result)

Finally I have string of decimal values separated by comma as follows:

18770, 17990, 20334, 15, 16727, 17750, 28006, 8308, 18, 0, 1, 2, 48000, 0, 60928, 2, 4, 16, 0, 24934, 29795, 4, 0, 54223, 3, 24932, 24948, 20284, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

Of course previous posts on SO were of immense help :)

Upvotes: 0

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

Copy the code that defines the array to a file called "clip.h".

Write a small c program that #include "clip.h" and use a simple loop to write the data in the desired format. Run the program on your desktop computer. It could look something like this:

#include <stdio.h>
#include <stdint.h>
#include "clip.h"
#define NUMBERS_PER_LINE 20

int main(void) {
    int i;
    int sample_length = (sizeof AUDIO_SAMPLE)/(sizeof AUDIO_SAMPLE[0]);

    printf("AUDIO_SAMPLE = [ ");
    for (i=0; i < sample_length; i++) {
        printf("%" PRIu16 PRId16, AUDIO_SAMPLE[i]);  // Use the format specifier for uint16_t.
        if (i % NUMBERS_PER_LINE == NUMBERS_PER_LINE - 1) {
            // Insert line continuation mark
            printf(" ...\n  ");
        }
    }
    return 0;
}

The program will write the matlab code on stdout, so you need to redirect it to the desired file.

Upvotes: 1

Related Questions