Need help converting hex string to time in C# - string

I have issues understanding how to convert a hex value to a duration.
Here are some examples I've seen in the case I study:
2b3da = 2:44.986
2bf64 = 2:47.868
2c84a = 2:50.074
Could someone help to understand how those results are reached ?
Thanks.

string hex1;
string[] hex = new string[16];
hex[0] = hex1.Substring(0, 2);
hex[1] = hex1.Substring(2, 2);
hex[2] = hex1.Substring(4, 2);
hex[3] = hex1.Substring(6, 2);
hex[4] = hex1.Substring(8, 2);
hex[5] = hex1.Substring(10, 2);
hex[6] = hex1.Substring(12, 2);
hex[7] = hex1.Substring(14, 2);
//WE DONOT NEED TO REVERSE THE STRING
//CONVERTING TO INT SO WE CAN ADD TO THE BYTE[]
int[] decValue = new int[8];
for (int i = 0; i < 8; i++)
{
decValue[i] = Convert.ToInt32(hex[i], 16);
}
//CONVERTING TO BYTE BEFORE WE CAN CONVERT TO UTC
byte[] timeByte = new byte[8];
for (int i = 0; i < 8; i++)
timeByte[i] = (byte)decValue[i];
DateTime convertedTime = ConvertWindowsDate(timeByte);
textBox7.Text = convertedTime.ToString();
}
public static DateTime ConvertWindowsDate(byte[] bytes)
{
if (bytes.Length != 8) throw new ArgumentException();
return DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0));
}
Input : 0060CE5601D6CE01
Output : 31-10-2013 06:20:48

Related

How is a JPEG file formated?

I'm trying to write Bytes into a JPEG file, but I don't know the file's format and so the Bytes aren't in the right place of the image after writing into the file.
Does somebody know?
There are several markers that must appear in a JPEG file stream. I believe you can easily find the detailed description of the tags listed below on Internet.
SOI(0xFFD8) Start of Image
APP0(0xFFE0) Application
[APPn(0xFFEn)] (alternative)
DQT(0xFFDB) Define Quantization Table
SOF0(0xFFC0) Start of Frame
DHT(0xFFC4) Difine Huffman Table
SOS(0xFFDA) Start of Scan
DRI(0xFFDD) Define Restart Interval,(alternative)
...Image Stream
EOI(0xFFD9) End of Image
Those markers are followed by lengths in BIG ENDIAN format. You can decode Image Stream that exactly follows DRI using the huffman trees you decoded by DQT. For easier illustration, here are some functions I have written on my own in Java that decodes a header of JPEG, but without doubt there are many better JPEG Java projects on Github that you can refer to.
public int[][] cutX(byte[] x){
int s = x.length;int k = 1;int i = 2;int j;
d2[0][0]=Tool.unsignDecoder(x[1]);d2[1][0]=0;d2[2][0]=1;
while(d2[0][k-1]!=218){
d2[1][k]=i;
d2[0][k]=Tool.unsignDecoder(x[i+1]);
i=i+2+Tool.unsignDecoder(x[i+2])*256+Tool.unsignDecoder(x[i+3]);
d2[2][k]=i-1;
k=k+1;
}
for (j=s-1;j<i;j--){
if((Tool.unsignDecoder(x[j-1])==255)&&(Tool.unsignDecoder(x[j])==217)) break;
}
d2[0][k]=217;d2[1][k]=i;d2[2][k]=j+1;
return d2;
}
public void cutdata(byte[] x,int[][] d){
int a =Tool.indexOf_1(d[0],218);
int b =Tool.indexOf_1(d[0],217);
head = Arrays.copyOfRange(x, 0, d[2][a]+1);
byte[] im = Arrays.copyOfRange(x, d[1][b], d[2][b]-1);//-2:delete the last EOI message.
im1 = new byte[im.length];
int j=0;int i=0;//dynamically record the length of the revised sequence
while(i<im.length){
im1[j]=im[i];
j++;
if((i!=im.length-1)&&(Tool.unsignDecoder(im[i])==255)&&(Tool.unsignDecoder(im[i+1]))==0){
i++;//move rightward i
}
i++;
}
im1=Arrays.copyOfRange(im1, 0, j);//delete zeros in the end of the sequence
}
public void sof(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],192);
int i = d[1][z];
int[] temp = new int[19];
for(int j=0;j<19;j++){
temp[j]=Tool.unsignDecoder(x[j+i]);
}
int ph=i+5;int pw=i+7;
size[0] = Tool.unsignDecoder(x[ph])*256+Tool.unsignDecoder(x[ph+1]);
size[1] = Tool.unsignDecoder(x[pw])*256+Tool.unsignDecoder(x[pw+1]);
i += 11;//skip some unused letters
for(int j=0;j<3;j++){
int k = Tool.unsignDecoder(x[i]);
Q[j][0] = (k & 0xF0)/16;
Q[j][1] = k & 0x0F;
i += 3;
}
}
public void hfm(byte[] x,int[][] d){
//the DHT marker may appear several times in a JPEG, or several huffman trees can be found in a single DHT.
ArrayList res =Tool.indexOf(d[0],196);int thisLength;int pointer;int pointerOrigin;
int a;int huffLength = 0;
for(int z=0;z<res.size();z++){
a=(int) res.get(z);
pointer = d[1][a];pointerOrigin = d[1][a]+2;//please follow the straight-forward moving of this pointer
thisLength = Tool.unsignDecoder(x[pointer+2])*256+Tool.unsignDecoder(x[pointer+3]);
int[] temp = new int[thisLength+4];
for(int i=0;i<thisLength;i++){
temp[i]=Tool.unsignDecoder(x[pointer+i]);
}
pointer += 4;
while(huffLength<thisLength){
int mode = Tool.unsignDecoder(x[pointer]);pointer += 1;
int[] huff_num = new int[16];int total=0;
for(int i=0;i<16;i++){//码字总个数
huff_num[i] = x[pointer+i];total+=huff_num[i];
}
pointer +=16;int codePointer=0;int code=0;
int[][] huffmanTree = new int[3][total];
for(int i=0;i<16;i++){
if(i!=0){
code *= 2;
}
for(int j=0;j<huff_num[i];j++){
huffmanTree[0][codePointer]=i+1;
huffmanTree[1][codePointer]=code;
huffmanTree[2][codePointer]=Tool.unsignDecoder(x[pointer+codePointer]);
code++;codePointer++;
}
}
huffLength += pointer + codePointer - pointerOrigin;pointer += codePointer;
pointerOrigin = pointer;
switch(mode){
case(0):d0 = huffmanTree;break;
case(1):d1 = huffmanTree;break;
case(16):a0 = huffmanTree;break;
case(17):a1 = huffmanTree;break;
}
}
}
}
public void dri(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],221);
if(z!=-1){
int pointer = d[1][z];
int len = Tool.unsignDecoder(x[pointer+2])*256+Tool.unsignDecoder(x[pointer+3]);
int[] temp = new int[len+2];
for(int i=0;i<len;i++){
temp[i]=Tool.unsignDecoder(x[pointer+i]);
}
DRI = Tool.unsignDecoder(x[d[1][z]+4])*256+Tool.unsignDecoder(x[d[1][z]+5]);}
}
public void sos(byte[] x,int[][] d){
int z = Tool.indexOf_1(d[0],218);int a = d[1][z];
int len = Tool.unsignDecoder(x[a+2])*256+Tool.unsignDecoder(x[a+3]);
int[] temp = new int[len+2];
for(int j=0;j<len+2;j++){
temp[j]=Tool.unsignDecoder(x[j+a]);
}
int pointer = d[1][z]+6;
for(int j=0;j<3;j++){
treeSelect[j] = Tool.unsignDecoder(x[pointer]);
pointer += 2;
}
}

Smart card write error

i am working in smart card development. i have created MF (Master file), DF (dedicated File), EF (Elementary file) in smart card. EF file is used to store the data. This EF may be transparent file or record oriented file. i have written the data to transparent file using 00D1000008 540100 5303 010203 this command.i am also try to write the record oriented file using 00DD000008 540100 5303 010203 this command. but i got the error (6700 error code) wrong length. i need the solution to write the smart card EF record oriented file. please guide me.
Screen shot:
My code:
i have used winscard.dll
private void button_Transmit_Click(object sender, EventArgs e)
{
Status.Text = "";
byte[] baData = null;
string sClass = textBox_Class.Text;
string sIns = textBox_CLA.Text;
string sP1 = textBox_P1.Text;
string sP2 = textBox_P2.Text;
string sP3 = textBox_P3.Text;
sP3 = sP3.ToUpper();
int k1 = 70;
string sData = textBox1.Text;
byte bP1 = 0;
byte bP2 = 0;
byte bP3 = 0;
byte bClass = byte.Parse(sClass, NumberStyles.AllowHexSpecifier);
byte bIns = byte.Parse(sIns, NumberStyles.AllowHexSpecifier);
if (sP1 != "" && sP1 != "#")
bP1 = byte.Parse(sP1, NumberStyles.AllowHexSpecifier);
if (sP2 != "" && sP2 != "#")
bP2 = byte.Parse(sP2, NumberStyles.AllowHexSpecifier);
int integer = int.Parse(sP3, NumberStyles.AllowHexSpecifier);
byte bLe = (byte)k1;
if (integer != 0 && sData.Length != 0)
{
baData = new byte[integer];
for (int nJ = 0; nJ < sData.Length; nJ += 2)
baData[nJ / 2] = byte.Parse(sData.Substring(nJ, 2), NumberStyles.AllowHexSpecifier);
bLe = 0;
}
UInt32 m_nProtocol = (uint)PROTOCOL.Undefined;
uint RecvLength = 0;
byte[] ApduBuffer = null;
IntPtr ApduResponse = IntPtr.Zero;
SCard_IO_Request ioRequest = new SCard_IO_Request();
ioRequest.m_dwProtocol = m_nProtocol;
ioRequest.m_cbPciLength = 8;
if (baData == null)
{
ApduBuffer = new byte[4 + ((bLe != 0) ? 1 : 0)];
if (bLe != 0)
{
ApduBuffer[4] = (byte)bLe;
}
}
else
{
if (textBox1.Text.Length > 8)
{
ApduBuffer = new byte[5 + baData.Length];
Buffer.BlockCopy(baData, 0, ApduBuffer, 5, baData.Length);
ApduBuffer[4] = (byte)(baData.Length);
}
//read binary
else
{
ApduBuffer = new byte[5 + baData.Length + 1];
Buffer.BlockCopy(baData, 0, ApduBuffer, 5, baData.Length);
ApduBuffer[4] = (byte)(baData.Length);
ApduBuffer[5 + baData.Length] = 255;
}
}
ApduBuffer[0] = bClass;
ApduBuffer[1] = bIns;
ApduBuffer[2] = bP1;
ApduBuffer[3] = bP2;
m_nLastError = SCardTransmit(scard.m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioRequest, ApduResponse, ref RecvLength);
textBox2.Text = "";
byte[] caReadersData = new byte[RecvLength];
if (m_nLastError == 0)
{
ApduResponse = Marshal.AllocHGlobal((int)RecvLength);
if (m_nLastError == 0)
{
m_nLastError = SCardTransmit(scard.m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioRequest, ApduResponse, ref RecvLength);
if (RecvLength > 2)
{
for (int nI = 0; nI < RecvLength - 2; nI++)
{
caReadersData[nI] = Marshal.ReadByte(ApduResponse, nI);
//kl[nI] = Marshal.ReadByte(ApduResponse, nI);
//result = string.Format("{0:X02}", caReadersData[nI]);
//Status.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
textBox2.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
//result = Status.Text;
}
}
else
{
for (int nI = 0; nI < RecvLength; nI++)
{
caReadersData[nI] = Marshal.ReadByte(ApduResponse, nI);
Status.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
}
}
}
}
Marshal.FreeHGlobal(ApduResponse);
}
Edit:
READ COMMAND is working fine. see the screen shot
It seems that you use an undefined coding of P2 with the odd instruction UPDATE RECORD command. Also, you have to specify the record number in P1. For the three least significant bits use
100-Replace
101-Logical AND
110-Logical OR
111-Logical XOR
If you aim for writing / updating complete records of small length, you might consider using the commands with even instruction. Then you can drop the offset DO (0x54) and only transmit the complete record (value of the discretionary data DO (0x53)).

Silverlight Speex playing at fast rate

I'm using Speex to encode the raw data but after I decode the data the audio plays at a faster rate because it makes you sound like a chipmunk. I'm using NSpeex and Silverlight 4.
8kHz Sampling
Encoding Function:
JSpeexEnc encoder = new JSpeexEnc();
int rawDataSize = 0;
public byte[] EncodeAudio(byte[] rawData)
{
var encoder = new SpeexEncoder(BandMode.Narrow);
var inDataSize = rawData.Length / 2;
var inData = new short[inDataSize];
for (var index = 0; index < rawData.Length; index += 2)
{
inData[index / 2] = BitConverter.ToInt16(rawData, index);
}
inDataSize = inDataSize - inDataSize % encoder.FrameSize;
var encodedData = new byte[rawData.Length];
var encodedBytes = encoder.Encode(inData, 0, inDataSize, encodedData, 0, encodedData.Length);
byte[] encodedAudioData = null;
if (encodedBytes != 0)
{
encodedAudioData = new byte[encodedBytes];
Array.Copy(encodedData, 0, encodedAudioData, 0, encodedBytes);
}
rawDataSize = inDataSize; // Count of encoded shorts, for debugging
return encodedAudioData;
}
Decoding Function:
SpeexDecoder decoder = new SpeexDecoder(BandMode.Narrow);
public byte[] Decode(byte[] encodedData)
{
try
{
short[] decodedFrame = new short[8000]; // should be the same number of samples as on the capturing side
int decoderBytes = decoder.Decode(encodedData, 0, encodedData.Length, decodedFrame, 0, false);
byte[] decodedData = new byte[encodedData.Length];
byte[] decodedAudioData = null;
decodedAudioData = new byte[decoderBytes * 2];
for (int shortIndex = 0, byteIndex = 0; byteIndex < decoderBytes; shortIndex++)
{
BitConverter.GetBytes(decodedFrame[shortIndex + byteIndex]).CopyTo(decodedAudioData, byteIndex * 2);
byteIndex++;
}
// todo: do something with the decoded data
return decodedAudioData;
}
catch (Exception ex)
{
ShowMessageBox(ex.Message.ToString());
return null;
}
}
Playing the audio:
void PlayWave(byte[] PCMBytes)
{
byte[] decodedBuffer = Decode(PCMBytes);
MemoryStream ms_PCM = new MemoryStream(decodedBuffer);
MemoryStream ms_Wave = new MemoryStream();
_pcm.SavePcmToWav(ms_PCM, ms_Wave, 16, 8000, 1);
WaveMediaStreamSource WaveStream = new WaveMediaStreamSource(ms_Wave);
mediaElement1.SetSource(WaveStream);
mediaElement1.Play();
}
Sorry guys for the late response but I figured out what the problem was.
Inside my decode function I loop through the decoded short array but I'm only copying half of the bytes into my new byte array.
It needs to look something like this:
decodedAudioData = new byte[decoderBytes * 2];
for (int shortIndex = 0, byteIndex = 0; shortIndex < decodedFrame.Length; shortIndex++, byteIndex += 2)
{
byte[] temp = BitConverter.GetBytes(decodedFrame[shortIndex]);
decodedAudioData[byteIndex] = temp[0];
decodedAudioData[byteIndex + 1] = temp[1];
}

how to create a waveform display from audio file using J2ME

I'm beginner in J2ME and want to develop a mobile music editor with waveform display embedded as my project.
Is there anyone who can help me, or give me some tutorial how to encode the audio file into waveform display?
This will generate waveform from audio file using nAudio...
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strPath = Server.MapPath("audio/060.mp3");
string SongID = "2";
byte[] bytes = File.ReadAllBytes(strPath);
WriteToFile(SongID,strPath, bytes);
Response.Redirect("Main.aspx");
}
private void WriteToFile(string SongID, string strPath, byte[] Buffer)
{
try
{
int samplesPerPixel = 128;
long startPosition = 0;
//FileStream newFile = new FileStream(GeneralUtils.Get_SongFilePath() + "/" + strPath, FileMode.Create);
float[] data = FloatArrayFromByteArray(Buffer);
Bitmap bmp = new Bitmap(1170, 200);
int BORDER_WIDTH = 5;
int width = bmp.Width - (2 * BORDER_WIDTH);
int height = bmp.Height - (2 * BORDER_WIDTH);
NAudio.Wave.Mp3FileReader reader = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
NAudio.Wave.WaveChannel32 channelStream = new NAudio.Wave.WaveChannel32(reader);
int bytesPerSample = (reader.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
Pen pen1 = new Pen(Color.Gray);
int size = data.Length;
string hexValue1 = "#009adf";
Color colour1 = System.Drawing.ColorTranslator.FromHtml(hexValue1);
pen1.Color = colour1;
Stream wavestream = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
wavestream.Position = 0;
int bytesRead1;
byte[] waveData1 = new byte[samplesPerPixel * bytesPerSample];
wavestream.Position = startPosition + (width * bytesPerSample * samplesPerPixel);
for (float x = 0; x < width; x++)
{
short low = 0;
short high = 0;
bytesRead1 = wavestream.Read(waveData1, 0, samplesPerPixel * bytesPerSample);
if (bytesRead1 == 0)
break;
for (int n = 0; n < bytesRead1; n += 2)
{
short sample = BitConverter.ToInt16(waveData1, n);
if (sample < low) low = sample;
if (sample > high) high = sample;
}
float lowPercent = ((((float)low) - short.MinValue) / ushort.MaxValue);
float highPercent = ((((float)high) - short.MinValue) / ushort.MaxValue);
float lowValue = height * lowPercent;
float highValue = height * highPercent;
g.DrawLine(pen1, x, lowValue, x, highValue);
}
}
string filename = Server.MapPath("image/060.png");
bmp.Save(filename);
bmp.Dispose();
}
catch (Exception e)
{
}
}
public float[] FloatArrayFromStream(System.IO.MemoryStream stream)
{
return FloatArrayFromByteArray(stream.GetBuffer());
}
public float[] FloatArrayFromByteArray(byte[] input)
{
float[] output = new float[input.Length / 4];
for (int i = 0; i < output.Length; i++)
{
output[i] = BitConverter.ToSingle(input, i * 4);
}
return output;
}
}

JavaME: Convert String to camelCase

What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.
Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...
String str = "Hello, there, everyone?";
StringBuffer result = new StringBuffer(str.length());
String strl = str.toLowerCase();
boolean bMustCapitalize = false;
for (int i = 0; i < strl.length(); i++)
{
char c = strl.charAt(i);
if (c >= 'a' && c <= 'z')
{
if (bMustCapitalize)
{
result.append(strl.substring(i, i+1).toUpperCase());
bMustCapitalize = false;
}
else
{
result.append(c);
}
}
else
{
bMustCapitalize = true;
}
}
System.out.println(result);
You can replace the convoluted uppercase append with:
result.append((char) (c - 0x20));
although it might seem more hackish.
With CDC, you have:
String.getBytes();//to convert the string to an array of bytes
String.indexOf(int ch); //for locating the beginning of the words
String.trim();//to remove spaces
For lower/uppercase you need to add(subtract) 32.
With these elements, you can build your own method.
private static String toCamelCase(String s) {
String result = "";
String[] tokens = s.split("_"); // or whatever the divider is
for (int i = 0, L = tokens.length; i<L; i++) {
String token = tokens[i];
if (i==0) result = token.toLowerCase();
else
result += token.substring(0, 1).toUpperCase() +
token.substring(1, token.length()).toLowerCase();
}
return result;
}
Suggestion:
May be if you can port one regexp library on J2ME, you could use it to strip spaces in your String...
Try following code
public static String toCamel(String str) {
String rtn = str;
rtn = rtn.toLowerCase();
Matcher m = Pattern.compile("_([a-z]{1})").matcher(rtn);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
rtn = sb.toString();
return rtn;
}
I would suggest the following simple code:
String camelCased = "";
String[] tokens = inputString.split("\\s");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
camelCased = camelCased + token.substring(0, 1).toUpperCase() + token.substring(1, token.length());
}
return camelCased;
I would do it like this:
private String toCamelCase(String s) {
StringBuffer sb = new StringBuffer();
String[] x = s.replaceAll("[^A-Za-z]", " ").replaceAll("\\s+", " ")
.trim().split(" ");
for (int i = 0; i < x.length; i++) {
if (i == 0) {
x[i] = x[i].toLowerCase();
} else {
String r = x[i].substring(1);
x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r;
}
sb.append(x[i]);
}
return sb.toString();
}
check this
import org.apache.commons.lang.WordUtils;
String camel = WordUtils.capitalizeFully('I WANT TO BE A CAMEL', new char[]{' '});
return camel.replaceAll(" ", "");

Resources