1

in java I use this code too read mp3 file in to buffer

byte[] buffer = new byte[12];
stream.read(buffer, offset, 12 - offset); 
for(int i = 0; i<buffer.length ; i++){
     Log.e("buff","buff "+ buffer[i]);
}

and here's result of buffer

69 82 0 0 0 5 0 0 0 -50 -76 -42

in swift 3.0

var buffer = Data()
let file = try FileHandle(forReadingFrom: urlLocal)
file.seek(toFileOffset: 0)
buffer = file.readData(ofLength: 12)
for  i in  0...(buffer.count-1){
            print(buffer[i])
}

and here is result of buffer

69 82 0 0 0 5 0 0 0 206 180 214

I think Data in swift use Unit8 data type that reason I have difference output. My question, in swift how can I get output same java. thank you so much !

EDIT : output code

er lear
  • 13
  • 4
  • 1
    Update both sets of code showing how you print the buffers. – rmaddy Oct 18 '16 at 04:51
  • looks like java prints out its values signed, while swift is unsigned, aka -50 = 206 etc ... -128 - 128 vs 0 - 256 – Fonix Oct 18 '16 at 05:04
  • FYI - since you are dealing with byte data, I'd suggest you update the Java code to print like the Swift code. – rmaddy Oct 18 '16 at 05:13

2 Answers2

1

Data is a collection of unsigned bytes (UInt8). If you really want to print them as signed bytes then you can use Int8(bitPattern:) which creates a signed value with the same memory representation:

let buffer = Data(bytes: [69, 82, 0, 0, 0, 5, 0, 0, 0, 206, 180, 214])
for byte in buffer {
    print(Int8(bitPattern: byte))
}
// 69 82 0 0 0 5 0 0 0 -50 -76 -42

Or create an [Int8] array from the data and print the array:

let signedByteArray = buffer.map { Int8(bitPattern: $0) } // [Int8]
print(signedByteArray)
// [69, 82, 0, 0, 0, 5, 0, 0, 0, -50, -76, -42]
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • this is what I need, thank you so much !. I really wanna give this answer one thumbs up but I dont have enough reputation now . sorry !! – er lear Oct 18 '16 at 08:55
0

In your java code you can try do this method which is quite straight forward to make it unsigned while printing

for(int i = 0; i<buffer.length ; i++){
     Log.e("buff","buff "+ (buffer[i] & 0xFF));
}
Community
  • 1
  • 1
Fonix
  • 11,447
  • 3
  • 45
  • 74